在 componentDidMount 上反应本机 setState 不起作用

React native setState on compnonentDidMount doesnt work

我正在使用 flux 并尝试在 React Native 应用程序的顶级组件中 componentDidMount setState。在 constructor 中,this.state = MainStore.getData(); 似乎可以很好地设置状态。但是出于某种原因 this.setState(data); 没有在我的 componentDidMount 中设置状态。这是我的顶级组件的代码和我的通量模式的商店。

组件:

constructor(props) {
  super(props);
  this.state = MainStore.getData();
}

componentDidMount() {
  MainStore.addChangeListener(this._onChange);
  var data = MainStore.getUpdatedData();
  console.log('data from store: ',data)
  this.setState(data);
  console.log('state: ',this.state)
}

商店:

var kidsBankData = {
  test:null
};

var kidsData = assign({}, EventEmitter.prototype, {
  getData: function() {
    return kidsBankData;
  },

  getUpdatedData: function(){
    newObj = {
      test:'test'
    }
    return newObj;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
});

我只是想让流程正常工作,所以我使用了一个测试对象。在我的组件中,第一个控制台日志是控制台日志 var data = MainStore.getUpdatedData(); 是正确的控制台日志 test:'test' 但是第二个日志显示状态仍然是 test:null 你可以看到它最初是什么constructor 从商店退回。

那么为什么 this.setState(data) 不更新状态?没有控制台错误,它只是没有设置状态。

状态仅在 componentDidMount 方法结束时更新,因此您不会立即在 console.log 中看到结果。事实上,React 框架聚合了所有的状态变化并一次性执行。没有即时的、中间的状态更新例如,如果你会做这样的事情:

componentDidMount: function() {
  // Get obj1 from some store
  this.setState(obj1)
  // Get obj2 from another store
  this.setState(obj2)
}

这相当于:

componentDidMount: function() {
  // Get obj1 from some store
  // Get obj2 from another store
  this.setState(data1: obj1.data, data2: obj2.data)
}