在 reactjs 中使用 npm uuid

Use npm uuid in reactjs

我有一个地方需要使用 npm uuid 包来生成唯一的 ID。安装uuid包后,使用方法如下:

const uuid = require('uuid/v1');
uuid();

但我有错误提示:

[eslint] Unexpected require(). (global-require)

我的函数如下:

someFunction = (i, event) => {
   if(someCondition) {
       //generate some unique id
       const uuid1 = require('uuid/v1');
       uuid1();
       //call some function and pass this id
       someFunction2(uuid1);
    } else{ 
      //generate some unique id
       const uuid2 = require('uuid/v1');
       uuid2();
       //call some function and pass this id
       someFunction2(uuid2);
    }

在 ReactJs 中使用 require 的最佳方式是什么。

你不必总是需要这个包。只需要一次,随处使用。

const uuidv1 = require('uuid/v1');

if (condition) {
    some_id = uuidv1();
    some_function(some_id);

} else {
    other_id = uuidv1();
    other_function(other_id);
}

就这么简单

试试这个:

import React from "react";
import ReactDOM from "react-dom";
import uuid from "uuid";

function App() {
  return (
    <div className="App">
      <h1>{uuid.v4()}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这是一个工作示例:https://codesandbox.io/s/0pr5vz48kv

在反应中使用import.

在 Nodejs 项目中使用 'require'。

如果你想在普通的nodejs项目中使用import,需要"babel"来设置。

以防万一你想使用 uuid v4,这是你可以在 React 中导入它的方法。

import uuid from 'uuid/v4'

对于 React JS:

import { v1 as uuidv1 } from 'uuid';
uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d'

您可以通过不同的方式导入

1----从命令行安装

npm i react-uuid
import uuid from 'react-uuid'

并用于关键变量,如下所示

key={uuid()}

2----我一直使用的更好的方法是

首先,安装

npm install uuid

然后导入

import { v1 as uuidv1 } from 'uuid';

并使用

uuidv1();

for more details read

截至 2020 年 9 月,我首先将类型安装为

yarn add @types/uuid

那么

import React from "react";
import ReactDOM from "react-dom";
import { v4 as uuidv4 } from 'uuid';

function App() {
  return (
    <div className="App">
      <h1>{uuidv4()}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

如果此代码以后不起作用,请参考this section of official docs.

import React from "react";
import ReactDOM from "react-dom";
import * as uuid from "uuid";

function App() {
  return (
    <div className="App">
      <h1>{uuid.v4()}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

你必须去这个文件夹=> 你的驱动器:/你的 projectfolder/node_modules/uuid/dist/v1 并查看您的 uuid 文件夹 默认情况下,这是在顶级文件夹中

import UUID From 'uuid/dist/v1'

将 React 与 typescript 版本 4.5.0 或更高版本一起使用。

  1. 运行: npm install --save @types/uuid

  2. 在包含文件“allTypes.d.ts”的根文件夹中创建目录“@types”并添加到那里

    declare module "uuid";

  3. 在compilerOptions下的ts.config.json中添加:

    "typeRoots": ["./node_modules/@types","./@types" ]

  4. 重新运行您的应用程序并在必要时导入
    import { v4 as uuidv4 } from "uuid";