让我们说我要更新的状态:
state = {
description: "",
notes: ""
}
如果我不需要使用prevState,只用一个对象更新状态,会有区别吗?
this.setState({description: "Blue"});
vs
this.setState((prevState)=> ({description: "Blue"}));
答案 0 :(得分:2)
我已经创建了一个demo来可视化差异
/* When we doing this state gets update after the for loops runs so,
this.state.count is same for each repeat so even if we expecting to
count increase by 5 its actually increment by 1 */
updateCountByFive = () => {
for (let a = 0; a < 5; a++) {
this.setState({
count: this.state.count + 1
});
}
};
/* In this case by using callback to set the new state,
react is smart enough to pass the latest count value to the callback
event if that new change not rendered */
updateCountByFiveCallback = () => {
for (let a = 0; a < 5; a++) {
this.setState(prevState => {
return {
count: prevState.count + 1
};
});
}
};
因此,当您需要使用当前状态来设置下一个状态时,最好使用回调版本,因为这样可以避免上述某些问题
react doc就是这样。
React可以将多个setState()调用批处理为一个更新,以提高性能。
由于this.props和this.state可能是异步更新的,因此不应依赖于它们的值来计算下一个状态。
有一个不错的article here