Reactjs 在用户单击“后,在React JS中创建一个新的唯一ID”;提交;

Reactjs 在用户单击“后,在React JS中创建一个新的唯一ID”;提交;,reactjs,state,jsx,Reactjs,State,Jsx,你能帮我在React JS应用程序中添加最后一段代码吗?因此,我的程序的初始状态为: state = { players: [ { name: “Player 1", score: 0, id: 1, } 表单中还有一个带有事件侦听器的按钮,允许用户添加新玩家。使用提供的数据更新初始状态的函数如下所示: handleAddPlayer = (name) => { this.setSta

你能帮我在React JS应用程序中添加最后一段代码吗?因此,我的程序的初始状态为:

state = {
    players: [
      {
        name: “Player 1",
        score: 0,
        id: 1,
      }

表单中还有一个带有事件侦听器的按钮,允许用户添加新玩家。使用提供的数据更新初始状态的函数如下所示:

  handleAddPlayer = (name) => {
    this.setState({
      players: [
        ...this.state.players,
        {
          name: name,
          score: 0,
          id: , // <- Make it unique every time a new player is added
        },
      ],
    });
  };

handleAddPlayer=(名称)=>{
这是我的国家({
玩家:[
…这个州的球员,
{
姓名:姓名,,
分数:0,

id:,//您可以使用
UUID
来实现:

const genUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}
// later in your code
id: genUUID()
您可以使用此功能,也可以安装执行相同操作的库。

您可以使用

  • 索引
    id:this.state.players.length+1
    [不推荐]
  • 当前时间戳
    +新日期()
    unix历元时间\\例如1593203793398
  • 像这样的图书馆