reactJS如何阻止它监听ajax请求 [英] reactJS how to stop it listening to ajax request

查看:24
本文介绍了reactJS如何阻止它监听ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 componentdidmount 中有 ajax 调用.然后在 ajax 承诺中设置状态.

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?

推荐答案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆