//Example #1 - I KNOW THIS IS WRONG
this.state.myCount = this.state.myCount + 42;
//Example #2 - Why is this wrong ?
this.setState({
myCount: this.state.myCount + 42,
})
//Example #3 - proper way, as per React docs
this.setState( (prevState, props) => ({
myCount: prevState.myCount + 42
}));
现在,我一直在使用Example#2,而在进行React的3年以上中却没有遇到任何错误。
为什么Example#2错误,有人可以举一个反例,它实际上会在控制台中显示一个错误?
答案 0 :(得分:0)
来自Medium的this帖子的示例和来自Why is setState in reactjs Async instead of Sync?帖子的解决方案
// assuming state.count === 0
this.setState({count: state.count + 1});
this.setState({count: state.count + 1});
this.setState({count: state.count + 1});
// state.count === 1, not 3
//Solution
this.setState((prevState, props) => ({
count: prevState.count + props.increment
}));
他们在文章中声称:
不能保证对setState调用的同步操作 和呼叫可以批量进行以提高性能。