Multiple setStates do not accumulate into one update/render…?

后端 未结 2 1783
感情败类
感情败类 2021-01-14 09:24

I remember how surprised I was when I found out that setState was async. Now I stumbled upon a \"strange\" behaviour that doesn\'t fit into my understanding of

相关标签:
2条回答
  • 2021-01-14 10:15

    First you have incorrect seTtimeout notation. It accepts first as function that needs to be called after a particular time. It is recommended to do this after mounting the component. In your case function gets called and doesn't wait for timer you can try this by changing the time to 1000ms. here is correct implementation:

    class SomeComponent extends React.Component {
    
    
     constructor(props) {
        super(props);
        this.state = {
          prop1: 1,
          prop2: 2
        };
      }
    
      componentDidMount(){
        setTimeout(()=>{
          this.changeProp1()
        },100);
      }
    
      componentDidUpdate() {
        console.info("componentDidUpdate called");
      }
    

    Further setState only gets batched for synthetic event like onClick and doesn't re render till the end of handler execution. For setTimeoutand AJAX, states updates aren't batched. here is the more info about setState batch process.

    0 讨论(0)
  • 2021-01-14 10:18

    As linked section of the reference says,

    React may batch multiple setState() calls into a single update for performance.

    It shouldn't update state in batch, at least in React 16.

    As extensively explained in related answer by Dan Abramov of React team, the state is currently updated in batch only from event listeners, also on synchronous setState calls in lifecycle hooks (componentDidMount, componentDidUpdate). This is expected to be changed in React 17.

    In React 16, unstable_batchedUpdates should be explicitly used to unconditionally update the state in batch (a demo):

    setTimeout(() => {
      ReactDOM.unstable_batchedUpdates(() => {
        this.changeProp1();
      });
    }, 100);
    
    0 讨论(0)
提交回复
热议问题