Skip to content Skip to sidebar Skip to footer

(react.js )initial State Generated Randomly. How To Prevent It From Regenerate Each Time I Handle An Event?

I am building a game that players can attack each other by turn. So first I set the name, jobmanually and generate life,damage,magic randomly in componentWillMount(). I hope that

Solution 1:

I noticed that you do a lot of:

let players = this.state.players

which you are not supposed to do. Array is an object in js so here you are passing by reference. This means that every modification to the var players actually has side effects and modifies the state which you should never do. I generally recommend to never use in-place operations like splice, and to always use a copy of the state. In this case you can do:

let players = this.state.players.slice()

and from then on any modification to the players var does NOT affect the state. Double check you are not doing this anywhere else in your code. On top of that you should use the constructor only to set up and initiate your state. Otherwise every time the componentWillMount method is called your state is regenerated which is probably not the behavior you are expecting.

EDIT

I figured I could give you more pointers for what you are trying to do with arrays, as a general rule of thumb I follow this approach. If my new state has an array field which is a subset of the previous one then I use the .filter method, if the array of my new state needs to update some of its entries then I use the .map method. To give you an example on player deletion, I would have done it this way:

handleDeletePlayer(id) {
  this.setState(prevState => ({
    players: prevState.players.filter(player => player.id !== id)
  }));
}

Solution 2:

Your initial state should be generated in the constructor. This is done only once and will not be repeated when components props are updated.

Post a Comment for "(react.js )initial State Generated Randomly. How To Prevent It From Regenerate Each Time I Handle An Event?"