【发布时间】:2015-12-12 05:20:50
【问题描述】:
我遇到了一个问题,我通过在componentDidMount 中执行 AJAX 调用来加载初始数据,并在回调中为所述 AJAX 调用设置状态。我还希望在之后立即处理我的数据,所以我在setState 回调中调用了另一个函数。以下是我的代码的 sn-p:
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 是在我的构造函数中设置的初始值。任何意见将不胜感激。
编辑
所以我想我在我的代码 sn-p 中遗漏了一些东西。我的过滤函数实际上调用this.setState 将过滤后的数据存储在状态中。我认为这实际上是导致我的问题的原因。
修改后的sn-p:
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');
}
};
}
【问题讨论】:
标签: javascript reactjs ecmascript-6