无法在componentWillMount()中看到数据?

时间:2017-11-17 04:13:24

标签: javascript jquery reactjs jquery-csv

我正在Jquery中执行.get()请求并更新状态。

我的问题是:

为什么我无法在console.log(this.state.storage)以及componentWillMount()中看到componentDidMount()中的数据,但我确实在render()中获得了输出?

此外,我还需要对获取的数据进行操作,在生命周期中我应该这样做吗?



constructor() {
  super();
  this.state = {
    storage: []
  }
}

componentWillMount() {
  $.get('data.csv', (data) => this.setState({
    storage: data
  }));
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return ( 
    <div >{this.state.storage}</div> //Do get the Output
    );
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

this.setState在更新组件状态方面是异步的; documentation here。如果您想查看this.setState影响的更改,则必须将回调传递给函数调用

此外,您可以在$.get方法的回调中执行操作,如下所示

constructor() {
  super();
  this.state = {
    storage: []
  }
}

myCustomOperations = (data) => {
  // do custom operations here with data
}

componentWillMount() {
  $.get('data.csv', (data) => {
    this.myCustomOperation(data);
    this.setState({
      storage: data
    }, () => {
      console.log(this.state.storage); // correct output
      // this.myCustomOperation(this.state.storage) // if you want to do the custom operation after the data has been put into the state
    });
  });
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return ( 
    <div >{this.state.storage}</div> //Do get the Output
    );