this.state与此对象中的状态不同
this.state not the same as state in this object
我遇到了一个问题,我通过在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));
setState会导致一个主管重新渲染,使您在它之后所做的任何事情都与react无关。您需要稍后挂接到组件生命周期中,如componentWillUpdate或componentDidUpdate来运行您的过滤函数。
相关文章:
- js,对象's状态监视
- redux 中状态对象的结构
- 如何将状态对象/数据传递给(异步)ajax 回调
- 你能在js中获得以前的历史状态对象吗
- 更新HTML5历史中以前的状态对象
- stampit.js“状态”对象不是实例安全的
- 相位器.js获取给定的无效相位器状态对象
- 使用 React 创建的表单不会更新支持状态对象
- AngularJs :将 stateParams 值附加到状态对象中的自定义数据
- Redux 的 .getState() 不应该返回状态对象的副本
- Nodejs使用回调函数缓存有状态对象
- 我可以只返回状态对象的一部分而不是整个状态对象的新副本吗
- 处理一个巨大的状态对象
- 访问pushState状态对象内容
- 调用mapStateToProps似乎传递了错误的状态对象
- 试图通过将状态对象放入变量来压缩我的ui-router状态定义.并# 39;t工作
- React路由器-动态路由-通过路由器访问状态对象
- HTML5历史API-状态对象的最大大小是多少
- React:您可以将setState与现有的状态对象一起使用吗
- Pubnub:无法获得带有存在事件的状态对象