Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
React的setState是异步的。在更新依赖于this.props或this.state ,使用this.setState里传Object的写法是不可靠的。在复杂应用中如果this.setState被调用多次可能会出错。
原因是React的更新是异步的,使用按批更新来提升DOM的性能。
可靠的写法是在需要依赖this.props
或 this.state
更新值的时候,向this.setState传递一个函数。
不可靠的写法:
this.setState({showForm : !this.state.showForm});
可靠的写法:
this.setState(function(prevState, props){
return {showForm: !prevState.showForm}
});