(React.js)初始状态是随机生成的.如何防止每次处理事件时重新生成? [英] (React.js )Initial state generated randomly. How to prevent it from regenerate each time I handle an event?
问题描述
我正在构建一个游戏,players
可以轮流相互攻击.因此,首先我手动设置name
,job
,并在componentWillMount()
中随机生成life
,damage
,magic
.
I am building a game that players
can attack each other by turn. So first I set the name
, job
manually 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
推荐答案
我注意到您做了很多事情:
I noticed that you do a lot of:
let players = this.state.players
您不应该这样做. Array
是js中的一个对象,因此您在这里通过引用传递.这意味着对var players
的每次修改实际上都有副作用,并且会修改您永远不应该执行的状态.我通常建议不要使用像splice
这样的in-place
操作,并且始终使用状态副本.在这种情况下,您可以执行以下操作:
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()
,从那时起,对players
var的任何修改都不会影响状态.仔细检查您在代码的其他任何地方都没有这样做.最重要的是,您应该仅使用构造函数来设置和初始化状态.否则,每次调用componentWillMount
方法时,都会重新生成您的状态,这可能不是您期望的行为.
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.
编辑
我认为我可以为您提供更多关于数组的提示,作为一般经验法则,我遵循这种方法.如果我的新状态的数组字段是前一个数组的子集,则使用.filter
方法,如果我的新状态的数组需要更新其某些条目,则使用.map
方法.为了给您提供有关删除播放器的示例,我可以这样进行:
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)
}));
}
这篇关于(React.js)初始状态是随机生成的.如何防止每次处理事件时重新生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!