React中一般情况下state是异步更新的,在合成事件和生命周期中一般是异步更新的,它会将几次更新状态合并在一起更新。
React同步更新方法:
一、使用回调函数:
this.setState((prevState, props) => ({
count: prevState.count + 1
}));
二、使用计时器:
setTimeout(() => {
this.changeValue();
}, 0);
三、使用原生事件:
componentDidMount(){
document.body.addEventListener('click', this.changeValue, false)
}
changeValue = () => {
this.setState({counter: this.state.counter+1})
}