2017-02-06 39 views
1

我在下面的代码反应:ACCES this.state变量阵营

getInitialState: function() { 
    var state= { 
     data: {} 
    }; 

    fetch(this.props.dataurl) 
     .then(function(response) { 
      return response.json(); 
     }) 
     .then(function(result) { 
      this.setState({data:result}); 
     }.bind(this)); 
    return this.state; 

}, 
componentDidMount: function() { 
    console.log(this); 
    console.log(this.state); 
} 

所以在getInitialState功能我从取结果初始化状态变量数据,然后我要访问的数据变量第二个功能componentDidMount

我的问题是,this.state返回数据对象为空,但当我尝试登录this我收到数据变量与数据中。

那么,为什么我有这种行为,我该如何解决它?

回答

1

componentDidMount不保证异步fetch已完成。

您应该定义componentDidUpdate,当状态发生变化时会调用它,以便您可以对新数据执行任何操作。

componentDidUpdate(object prevProps, object prevState) 

请参阅React Lifecycle