React中的setState是异步的?

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,从而走的是类似异步的那一套。

为什么setState设计成伪异步
    setState设计为伪异步,可以显著提升性能 如果每次用setState都进行更新一次,多次调用,render的执行频率非常高,重新渲染的频率高,效率低 最好的办法是获取多个更新转态进行合并,并做一次批处理更新,可以大大提高更新的性能 如果更新了state但是没有去执行render函数,那么state和props不能保持同步,state和props不保持同步会导致一些开发问题。
经验分享 程序员 微信小程序 职场和发展