【问题标题】:Simplest way to generate unique Id onto a value grabbed from a form (React)在从表单中获取的值上生成唯一 ID 的最简单方法(React)
【发布时间】:2020-04-17 23:10:30
【问题描述】:

我试图从输入中获取值,为其分配一个唯一的 id,然后将名称和 id 传递给 addFolder() 函数。然后对象将被推到状态文件夹数组的末尾。我的主要问题是尝试创建一个唯一的 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


    【解决方案1】:

    您应该检查这个库 uuid 以获取生成唯一 ID 的反应。 你有 5 个版本来生成它。

    npm install uuid --save

    import { v1 as uuidv1 } from 'uuid';
    
    //This is your unique id
    const id = uuidv1();
    
    

    【讨论】:

      【解决方案2】:

      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
      */
      

      【讨论】:

        猜你喜欢
        • 2011-08-03
        • 1970-01-01
        • 2015-06-07
        • 2011-01-25
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多