我遇到了一个问题,我通过在 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.state
和 this。 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));
关于javascript - this.state 与此对象中的状态不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34236606/