Nanoid 不能用于 react-native

Nanoid can't be used in react-native

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

我希望这个社区有人能提供帮助。

提前致谢。

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

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

问题已解决

我已经使用以下功能解决了这个问题。

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

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

终于成功了。 :)

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

const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 10); 

您还可以将以下内容导入您的 App.jsx/tsx 或索引文件(如果您不介意额外的依赖项):

import 'react-native-url-polyfill/auto';
import 'react-native-get-random-values';

在此之后,您需要在需要使用它的地方工作:

import {nanoid} from 'nanoid';

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

import 'react-native-get-random-values'
import { nanoid } from 'nanoid'

来自Nano ID docs

React Native does not have built-in random generator. The following polyfill works for plain React Native and Expo starting with 39.x.

Check react-native-get-random-values docs and install it. Import it before Nano ID.