reactJS如何阻止它听取ajax请求

ang*_*iwi 1 reactjs axios

我在componentdidmount中调用了ajax.然后在ajax promise中使用setState.

代码是这样的

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?
}
Run Code Online (Sandbox Code Playgroud)

当我导航到其他路线时,这会导致错误'无法在未安装的组件上设置'.

所以我认为我应该做的是删除componentwillunmount中的axios listener.你会怎么做?

ctr*_*usb 6

一个非常简单的解决方案可能是在卸载时设置一个标志并在promise解析中使用它,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)