React use .push to add to an array with onClick

2019-07-24 20:53发布

问题:

I am attempting to add to my existing array which is called players (which is an external file "players.js" that's imported into my parent).

I can write:

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

And that works as ID is used for the key and the name is updated in the array.

However if I write

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

And on my button I have

    <div>
      <h4>Add A Player</h4>
      <input />
      <button onClick={this.handleAddPlayer}>Press to Add Player</button>
    </div>

And my state is as follows:

  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,
};

It does not work.

From here I have two questions:

  1. why won't it update when I click the button but works before not as a function?

  2. I would like to put a name into the input and generate a unique key that's added into my array, players.js

I've tried concatenate and had not a lot of success.

回答1:

Players is a property on the state object, so you'll want to call setState to update the property:

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,
  });
};