Nanoid不能用于react-native

Moh*_*iya 7 react-native nanoid

我不知道当我在 React Native 中使用nanoid包时到底发生了什么,它显示了某种以下错误。我不确定。

\n

我希望有人能从这个社区得到帮助。

\n

提前致谢。

\n

场景:我只是导入到 nanoid 包中。

\n
import { nanoid } from 'nanoid';\n
Run Code Online (Sandbox Code Playgroud)\n
Error: React Native does not have a built-in secure random generator. If you don\xe2\x80\x99t need unpredictable IDs use `nanoid/non-secure`. For secure IDs, import `react-native-get-random-values` before Nano ID.    \nat node_modules\\react-native\\Libraries\\LogBox\\LogBox.js:148:8 in registerError\nat node_modules\\react-native\\Libraries\\LogBox\\LogBox.js:59:8 in errorImpl\nat node_modules\\react-native\\Libraries\\LogBox\\LogBox.js:33:4 in console.error\nat node_modules\\expo\\build\\environment\\react-native-logs.fx.js:27:4 in error\nat node_modules\\react-native\\Libraries\\Core\\ExceptionsManager.js:104:6 in reportException\nat node_modules\\react-native\\Libraries\\Core\\ExceptionsManager.js:171:19 in handleException\nat node_modules\\react-native\\Libraries\\Core\\setUpErrorHandling.js:24:6 in handleError\nat node_modules\\react-native\\Libraries\\polyfills\\error-guard.js:49:36 in ErrorUtils.reportFatalError   \nat node_modules\\metro\\src\\lib\\polyfills\\require.js:204:6 in guardedLoadModule\nat http://192.168.43.19:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false&minify=false:203661:3 in global code\n
Run Code Online (Sandbox Code Playgroud)\n

Moh*_*iya 10

问题解决了

我通过使用以下功能解决了这个问题。

所以我认为在nanoid使用的crypto模块中所以react-native它不存在。

为此,我们需要使用一个nanoid/non-secure模块。下面我也用过customAlphabet方法。

最后它起作用了。:)

import { customAlphabet } from 'nanoid/non-secure'; 

const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 10); 
Run Code Online (Sandbox Code Playgroud)


eck*_*ckc 10

添加react-native-get-random-values依赖,然后在 Nano ID 之前导入:

import 'react-native-get-random-values'
import { nanoid } from 'nanoid'
Run Code Online (Sandbox Code Playgroud)

来自Nano ID 文档

React Native 没有内置的随机生成器。以下 polyfill 适用于从 39.x 开始的普通 React Native 和 Expo。

检查react-native-get-random-values文档并安装它。在 Nano ID 之前导入。