如何解决设置反应状态的不同方法
//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错误,有人可以举一个反例,它实际上会在控制台中显示一个错误?
解决方法
来自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调用的同步操作 和呼叫可以批量进行以提高性能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。