React使用.push通过onClick添加到数组

sth*_*hig 1 javascript arrays ecmascript-6 reactjs

我试图将其添加到我的现有数组中,称为播放器(这是导入到我的父级中的外部文件“ players.js”)。

我可以写:

 players.push({
  name: 'Maul',
  id: 26
});
Run Code Online (Sandbox Code Playgroud)

它用作ID用作键,并且名称在数组中更新。

但是如果我写

   handleAddPlayer = () => {
    console.log('i am working');
    players.push({
      name: 'Maul',
      id: 26
    });
  };
Run Code Online (Sandbox Code Playgroud)

在我的按钮上

    <div>
      <h4>Add A Player</h4>
      <input />
      <button onClick={this.handleAddPlayer}>Press to Add Player</button>
    </div>
Run Code Online (Sandbox Code Playgroud)

我的状态如下:

  this.state = {
  id: players.id,
  totalScore: 0,
  countInfo: [],
  evilName: '',
  color: '#6E68C5',
  scoreColor: '#74D8FF',
  fontAwe: 'score-icon',
  incrementcolor: '',
  scoreNameColor: 'white',
  glow: '',
  buttonStyle: 'count-button-start',
  players,
};
Run Code Online (Sandbox Code Playgroud)

这是行不通的。

从这里我有两个问题:

  1. 为什么当我单击按钮时它不会更新,但以前不能作为功能运行?

  2. 我想在输入中输入一个名称,并生成一个唯一键,该键添加到我的数组players.js中

我已经尝试过串联,但没有成功。

Tua*_*ful 6

Players是状态对象的属性,因此您需要调用setState来更新该属性:

handleAddPlayer = () => {
  // create a clone of your array of players; don't modify objects on the state directly
  const players = this.state.players.slice(0);

  players.push({
    name: 'Maul',
    id: 26
  });

  this.setState({
    players: players,
  });
};
Run Code Online (Sandbox Code Playgroud)