reactJS how to stop it listening to ajax request

后端 未结 2 1956
深忆病人
深忆病人 2021-01-07 09:22

I have ajax call in componentdidmount. And and then setState inside the ajax promise.

The code is like this

componentDidMount(){
    axios.post(\'myd         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-07 09:53

    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;
    }
    

提交回复
热议问题