为了更好的实践,首先应该避免变异状态,如果在更新状态时需要状态值,则应考虑使用功能状态更新。这将有助于始终获得正确的值。
另一个要考虑的是,你正在使用的设置之后this.state.score
权。 setState
是异步,你做你的if
语句之后,可能会发生。为此,您应该考虑使用回调。
下面是与上面的建议,你的代码的修改版本;
this.setState((prevState) => {
const mushrooms = Object.assign({}, prevState.mushrooms);
mushrooms[foundMushroom.key].remaining = false;
return { mushrooms, score: (prevState.score + 1) };
},() => {
if (this.totalMushrooms === this.state.score) {
this.props.setTotalTime(startTime, steps);
this.props.history.push("/score");
}
});
我不知道你是如何使用this.state.mushrooms
价值,但有更好的表现,你可以做一个小的变化。如果你只想修改一个属性,那么你应该把你的属性上移一层。 mushrooms
我认为财产是不必要的。
示例数据
而是然后使用类似下面
this.state = {
mushrooms: {
mushA: {
remaining: true
},
mushB: {
remaining: false
},
mushC: {
remaining: true
}
}
};
您可以使用这样
this.state = {
mushA: {
remaining: true
},
mushB: {
remaining: false
},
mushC: {
remaining: true
}
};
这样你就可以更新像下面的状态。一次一个属性,我相信这会导致更好的性能更新。
this.setState((prevState) => {
const mushroom = Object.assign({}, prevState[foundMushroom.key], { remaining: false });
return { [foundMushroom.key]: mushroom, score: (prevState.score + 1) };
},() => {
if (this.totalMushrooms === this.state.score) {
this.props.setTotalTime(startTime, steps);
this.props.history.push("/score");
}
});
要更新ONY成绩? –
使用传播运算符 –
看看https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs –