0

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

我的问题是:

为什么我看不到 in 中的数据,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
    );

4

1 回答 1

1

this.setState更新组件状态的方式是异步的;文档在这里。如果您想查看受影响的更改,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
    );

于 2017-11-17T09:16:54.130 回答