javascript - 无法看到 componentWillMount() 中的数据?

标签 javascript jquery reactjs jquery-csv

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

我的问题是:

为什么我看不到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
    );

最佳答案

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
    );

关于javascript - 无法看到 componentWillMount() 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47343175/

相关文章:

javascript - css:更改规则集与使用选择器切换类/应用样式

javascript - 在jquery中获取所有具有相同名称属性的文本框的值

javascript - 如何从导航器对象中删除 serviceWorker 属性?

javascript - php 脚本中的 if/else 不适用于 ajax 请求

javascript - jQuery 解析巨大的响应失败

在浏览器中缩放时 CSS Media 查询行为不当,但在调整窗口大小时则不会

reactjs - 如何设置子组件而不在父组件中渲染它?

javascript - 如何将 Create-React-App 构建推送到 Heroku?

javascript - Highcharts 中plotBackgroundImage 的大小和偏移量

javascript - 如何传递 debounce 等待参数