this.state与此对象中的状态不同

this.state not the same as state in this object

本文关键字:状态 对象 state this      更新时间:2023-09-26

我遇到了一个问题,我通过在componentDidMount中执行AJAX调用来加载初始数据,并在回调中为所述AJAX调用设置状态。我还希望在之后立即处理我的数据,所以我在setState回调中调用另一个函数。下面是我的代码片段:

filterData(area) {
  console.log(this);
  console.log(this.state);
  console.log(this.state.data);
  ... // The implementation of my filter
}
componentDidMount() {
  let xhr = new XMLHttpRequest();
  xhr.onloadend = () => {
    console.log('* AJAX POST Response Received *');
    if (xhr.status >= 200 && xhr.status < 400) {
      this.setState({ data: JSON.parse(xhr.response) },
        this.filterData(this.area)
      );
    } else {
      console.error('[ERROR] Server returned invalid response');
    }
  };
}

当我查看this对象中的状态时,我可以找到我期望的正确状态数据,但this.statethis.state.data是在我的构造函数中设置的初始值。如有任何意见,我们将不胜感激。

编辑

所以我想我在代码片段中遗漏了一些内容。我的过滤函数实际上调用this.setState来将过滤后的数据存储在状态中。我想这就是造成我问题的原因。

修订片段:

filterData(area) {
  console.log(this);
  console.log(this.state);
  console.log(this.state.data);
  ... // The implementation of my filter
  this.setState({ filtered_data: filtered });
}

我目前的解决方案:

filterData(area, all_data) {
  if(this.state.data || all_data) {
    ... // The implementation of my filter
  }
  this.setState({ filtered_data: filtered });
}
componentDidMount() {
  let xhr = new XMLHttpRequest();
  xhr.onloadend = () => {
    console.log('* AJAX POST Response Received *');
    if (xhr.status >= 200 && xhr.status < 400) {
      this.filterData(this.area, JSON.parse(xhr.response));
    } else {
      console.error('[ERROR] Server returned invalid response');
    }
  };
}

setState的第二个参数必须是函数。试试这个:

this.setState({
    data: JSON.parse(xhr.response)
}, () => this.filterData(this.area));

setState会导致一个主管重新渲染,使您在它之后所做的任何事情都与react无关。您需要稍后挂接到组件生命周期中,如componentWillUpdate或componentDidUpdate来运行您的过滤函数。