React setState回调执行序列

时间:2015-09-10 06:25:04

标签: javascript reactjs

  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"));

结果是:

setTimeout调用:

在setState之前

setState回调 在setState之后

onclick电话:

在setState之前

在setState之后 setState回调

为什么执行顺序不同?

0 个答案:

没有答案