This.state does not match the state in this object

I'm having a problem when I load the source data by making an AJAX call in componentDidMountand setting the state in the callback for the specified AJAX call. I also want to manipulate my data right after I call another function in the callback setState. Below is a snippet of my code:

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

When I look at the state in an object this, I can find the correct state data that I expect, but this.statethey this.state.dataare also the initial values ​​set in my constructor. Any input would be appreciated.

Edit

, , . 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');
    }
  };
}
+4
2

setState . :

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

setState , , , . , componentWillUpdate componentDidUpdate, .

0

Source: https://habr.com/ru/post/1619600/


All Articles