将唯一ID生成到从表单(反应)获取的值上的最简单方法

问题描述 投票:0回答:2

我正在尝试从输入中获取值,为其分配一个唯一的ID,然后将名称和ID传递给addFolder()函数。然后,该对象将被推送到状态的folders数组的末尾。我的主要问题是尝试创建唯一的ID

    state = {
        name: '',
        id: ''
    }

    static contextType = Context;

    handleChange = (e) => {
        this.setState({name: e.target.value, id: ?? })  <-----------
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.context.addFolder(this.state.name, this.state.id)
    }

    render() {
        return (
            <div>
            <form 
            className='AddFolderForm'
            onSubmit={this.handleSubmit}
            >
                <h2>Add Folder</h2>
                <label >Name: </label>
                <input 
                type="text"
                id=??            <------------------
                placeholder="Folder Name"
                value={this.state.name}
                onChange={this.handleChange}
                />
                <button
                    type="submit"
                >Submit

                </button>
            </form>
            </div>
        )
    }
}


export default AddFolder
class App extends Component {
    state = {
        notes: [],
        folders: [],
    };

.... other code...

addFolder = (name, id) => {
        this.setState(prevState => ({
            folders: [...prevState.folders, {
                "name": `${name}`,
                "id": `${id}`,
            }]
          }))
    }
reactjs forms state
2个回答
1
投票

您应检查此库uuid以作出反应以生成唯一的ID。您有5个版本来生成它。

npm install uuid --save

import { v1 as uuidv1 } from 'uuid';

//This is your unique id
const id = uuidv1();


0
投票

Vanilla js中有一种简单的方法。如果使用此方法,则无需添加任何依赖项即可提高项目性能。

let uniqueId = (function () {
    let num = 0;
    return function (prefix) {
        prefix = String(prefix) || '';
        num += 1;
        return prefix + num;
    }
}
    ());
let id = uniqueId('id_');
console.log(id); // 'id_1'

lodash中还有另一种方法。使用以下命令添加lodash

npm i --save lodash

然后像下面的示例一样使用

let _ = require('lodash');

let id = _.uniqueId('id_');

console.log(id); // 'id_1'

let i = 10, ids = [];
while (i--) {
    ids.push(_.uniqueId('id_'));
}

console.log(ids[0]); // id_2
console.log(ids[9]); // id_11

如果您需要其他格式的ID,请按照以下方式操作。它也是高级Vanilla js解决方案。

let uniqueId = (function () {
    let c = 0,
    st = new Date();
    return function (prefix) {
        var t = new Date() - st,
        r = Math.floor(Math.random() * 1000),
        str;
        prefix = String(prefix) || '';
        str = '-' + c + '-' + t + '-' + r;
        c += 1;
        return prefix + str;
    }
}
    ());

console.log(uniqueId('id'));
console.log(uniqueId('id'));
console.log(uniqueId('id'));
setTimeout(function () {
    console.log(uniqueId('id'));
}, 1000);
/*
id-0-1-145
id-1-8-113
id-2-9-598
id-3-1018-910
*/
© www.soinside.com 2019 - 2024. All rights reserved.