React 中的setState是异步的吗?
观点:React中的setState可以是异步的,也可以是同步的。
1.什么时候是异步的
1.react中整合的事件调用setState,例如jsx中的onClick,或者是生命周期函数,这些内容调用setState是异步的。
render() {
return (
<div>
<div>{this.state.counter}</div>
<button onClick={()=>{this.increment()}}>增加</button>
</div>
)
}
//this.state.counter 为 0
increment(){
this.setState({
counter: this.state.counter+1
})
console.log(this.state.counter) // 0 ,不会加上1
}
2.什么时候是同步的:
不是react中整合的函数里面调用,例如: setTimeOut,setInterval,以及使用addEventListener的时候就是同步的:
constructor(){
super();
this.state = {
counter: 1,
}
}
componentDidMount(){
setTimeout(()=>{
this.setState({counter:10});
console.log(this.state.counter); //10
},2000)
}
render() {
return (
<div>
<div>{this.state.counter}</div>
<button onClick={()=>{this.increment()}}>增加</button>
</div>
)
}
上面的代码可以获取到 10
原因:
使用setState时,React中会去维护一个标识(isBatchingUpdates),判断是直接更新还是先暂存state进队列。setTimeout以及原生事件都会直接去更新state,因此可以立即得到最新state。而合成事件和React生命周期函数中,是受React控制的,其会将isBatchingUpdates设置为 true,从而走的是类似异步的那一套。