compnonentDidMount上的React本机setState不起作用

React native setState on compnonentDidMount doesnt work

本文关键字:setState 不起作用 本机 React 上的 compnonentDidMount      更新时间:2024-04-24

我正在使用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)
}