reactJS如何停止监听Ajax请求 [英] reactJS how to stop it listening to ajax request
本文介绍了reactJS如何停止监听Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在componentdidmount中有一个ajax调用.然后在ajax promise中设置setState.
I have ajax call in componentdidmount. And and then setState inside the ajax promise.
代码是这样的
componentDidMount(){
axios.post('mydomian.com/item/',this.state)
.then(function (response) {
const res = response.data
if (res.status === 'OK') {
this.setState({items :res.list})
}else{
console.log('can not load data', response)
}
}.bind(this))
}
componentWillUnmount(){
how to stop everything about axios?
}
当我导航到其他路线时,这会导致错误无法在未安装的组件上设置状态".
This causes error 'can not setstate on an unmounted component', when I navigate to other route.
所以我认为我应该做的是在componentwillunmount中删除axios监听器.你会怎么做?
So I think what I should do is remove axios listener in the componentwillunmount. How to would you do it?
推荐答案
一个非常简单的解决方案可以是在unmount上设置一个标志,并在promise分辨率内使用它,例如:
A very simple solution could be to set a flag on unmount and utilize it within the promise resolution, like so:
componentDidMount(){
axios.post('mydomian.com/item/',this.state)
.then(function (response) {
if (this.unmounted) return;
const res = response.data
if (res.status === 'OK') {
this.setState({items :res.list})
}else{
console.log('can not load data', response)
}
}.bind(this))
}
componentWillUnmount(){
this.unmounted = true;
}
这篇关于reactJS如何停止监听Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文