React setState回调执行序列

React setState callback execution sequence

本文关键字:执行 回调 setState React      更新时间:2023-09-26
  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电话:

设置状态设置状态回调设置状态后

onclick电话:

设置状态设置状态后设置状态回调

为什么执行顺序不同?

这与React的批处理更新机制有关。我在这个话题上不是很强,所以我不能给你一个明确的答案,但也许这里的讨论会给你一些启示:)https://groups.google.com/forum/!主题/reactjs LkTihnf6Ey8

setState是异步的。来自文档:

不能保证对setState的调用是同步的,为了提高性能,调用可能是批处理的。

因此,你只能安全地假设setState回调将在状态发生变化后执行。