本文介绍了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/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/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请求
发布评论