简体   繁体   English

反应setState回调执行顺序

[英]React setState callback execution sequence

  var SubOne = React.createClass({
    getInitialState(){
      return {
        current : 0
      };
    },

    render() {
      var that = this;
      var list = [
        1111,2222,3333,444
      ];
      var createItem = function(itemText, index) {
        return <li key={index} data-index={index} onClick={that._handleClick}>{itemText}</li>;
      };

      return <ul ref="list">{list.map(createItem)}</ul>;
    },

    componentDidMount(){
      var that = this;

      setTimeout(function(){
        that._handleClick();
      }, 2000);
    },

    _handleClick(){
      console.log("before setState");
      this.setState({
        current : 0
      },function(){
        console.log("setState callback");
      });
      console.log("after setState");
    }
  });

  React.render(<SubOne />, document.getElementById("example"));

The result is: 结果是:

setTimeout call: setTimeout调用:

before setState setState callback after setState 在setState之前setState回调在setState之后

onclick call: onclick通话:

before setState after setState setState callback 在setState之前setState setState回调之后

why the execution sequence is different? 为什么执行顺序不同?

This has to do with batching update mechanism of React. 这与React的批处理更新机制有关。 I'm not strong on the topic so I can't give you a clear answer, but maybe this discussion here would shed some light into you :) https://groups.google.com/forum/#!topic/reactjs/LkTihnf6Ey8 我对这个主题的看法不强,所以我无法给您一个明确的答案,但是也许这里的讨论会为您带来一些启发:) https://groups.google.com/forum/#!topic/reactjs/ LkTihnf6Ey8

setState is asynchronous. setState是异步的。 From the docs : 文档

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. 无法保证对setState的调用的同步操作,并且可能会为提高性能而批量调用。

Therefore you can only safely assume that the setState callback will be executed after the state has been mutated. 因此,您只能安全地假设将在状态发生setState后执行setState回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM