chunbin1 / blog

git actions + dumijs 写的博客
https://chunbin1.github.io/blog/
0 stars 0 forks source link

React setState的同步异步问题 #17

Open chunbin1 opened 3 years ago

chunbin1 commented 3 years ago

求输出结果

  1. class App extends React.Component{
    state = { number:0 }
    componentDidMount = ()=>{
    this.setState({ number:this.state.number + 1 },()=>{   console.log( 'callback1', this.state.number)  })
    console.log(this.state.number)
    this.setState({ number:this.state.number + 1 },()=>{   console.log( 'callback2', this.state.number)  })
    console.log(this.state.number)
    this.setState({ number:this.state.number + 1 },()=>{   console.log( 'callback3', this.state.number)  })
    console.log(this.state.number)
    }
    
    render(){
      return <div>
          { this.state.number }
      </div>
    }
    }

    输出: 0 0 0 callbackl1 1 callback2 1 callback3 1

chunbin1 commented 3 years ago
  1. 改成setTimeout

    class App extends React.Component{
    state = { number:0 }
    componentDidMount = ()=>{
    setTimeout(()=>{
      this.setState({ number:this.state.number + 1 },()=>{   console.log( 'callback1', this.state.number)  })
      console.log(this.state.number)
      this.setState({ number:this.state.number + 1 },()=>{   console.log( 'callback2', this.state.number)  })
      console.log(this.state.number)
      this.setState({ number:this.state.number + 1 },()=>{   console.log( 'callback3', this.state.number)  })
      console.log(this.state.number)
    })
    }
    
    render(){
      return <div>
          { this.state.number }
      </div>
    }
    }

    输出:callback1 1, 1, callback2 2, 2, callback 3, 3

chunbin1 commented 3 years ago
  1. 如何改为批量更新? 使用ReactDOM.unstable_batchedUpdates
chunbin1 commented 3 years ago
  1. 原理是什么? React中有个isBatchingEventUpdates控制是否批量更新。 在事件和生命周期中,会合并更新