(React.js )Initial state generated randomly. How to prevent it from regenerate each time I handle an event?

喜欢而已 提交于 2019-12-25 09:18:46

问题


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 every time I submit the attack form, certain amount of life with be reduced from the attacked person. But now every time I submit, the whole state is regenerated(with all kinds of bugs).

Can I do something to solve it?

app.js: https://ghostbin.com/paste/ype2y

attack.js: https://ghostbin.com/paste/wzm3m


回答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)
  }));
}



回答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.



来源:https://stackoverflow.com/questions/44545184/react-js-initial-state-generated-randomly-how-to-prevent-it-from-regenerate-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!