React:从 uuid 开始不推荐使用深度要求,请要求顶级模块

React: Deep requiring is deprecated as of uuid, Please require the top-level module

我的 React 应用程序成功显示按钮,但收到此错误。

index.js:1 从 uuid@7.x 开始不推荐像 const uuidv4 = require('uuid/v4'); 这样的深度要求。请在使用 Node.js CommonJS 模块时要求顶级模块,或者在为浏览器

捆绑时使用 ECMAScript 模块
import React, { Component } from 'react';
import { Container, ListGroup, ListGroupItem, Button } from 'reactstrap';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import uuid from 'uuid/v4';

class ShoppingList extends Component {
    state = {
        items: [
            { id: uuid(), name: 'Eggs' },
            { id: uuid(), name: 'Milk' },
            { id: uuid(), name: 'Steak' },
            { id: uuid(), name: 'Water' },
        ]
    }

    render() {
        const { items } = this.state;
        return (
            <Container>
                <Button 
                 color="dark"
                 style={{marginBottom: '2rem'}}
                 onClick={() => {
                    const name = prompt('Enter Item');
                    if (name) {
                        this.setState(state => ({
                           items: [...state.items, { id: uuid(), name }] 
                        }));
                    }
                }}
                >Add Item</Button>
            </Container>
        );
    }
}

export default ShoppingList;

您可以改用react-uuid

npm i react-uuid

用法

import uuid from "react-uuid";

在线试用:

这在最近更新库后发生了变化,现在您可以根据库描述导入 uuid:

"As of uuid@7 this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking”来删除死代码。相反,使用导入“

import { v4 as uuid_v4 } from "uuid";
uuid_v4()

... 或者对于 CommonJS:

const { v4: uuid_v4 } = require('uuid');
uuid_v4();