reactJS how to stop it listening to ajax request

后端 未结 2 1955
深忆病人
深忆病人 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;
    }
    
    0 讨论(0)
  • 2021-01-07 10:08

    I have find a great solution that has been defined by istarkov

    const makeCancelable = (promise) => {
      let hasCanceled_ = false;
    
      const wrappedPromise = new Promise((resolve, reject) => {
        promise.then((val) =>
          hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
        );
        promise.catch((error) =>
          hasCanceled_ ? reject({isCanceled: true}) : reject(error)
        );
      });
    
      return {
        promise: wrappedPromise,
        cancel() {
          hasCanceled_ = true;
        },
      };
    };
    

    How to use:

    const somePromise = new Promise(r => setTimeout(r, 1000));
    
    const cancelable = makeCancelable(somePromise);
    
    cancelable
      .promise
      .then(() => console.log('resolved'))
      .catch(({isCanceled, ...error}) => console.log('isCanceled', isCanceled));
    
    // Cancel promise
    cancelable.cancel();
    

    the solution has been found there.

    My implementation.

    Inside my function

    const promiseShareByEmail = makeCancelable(this.props.requestShareByEmail(obj.email, obj.url));
    
                promiseShareByEmail.promise.then(response => {
                    const res = response.data;
    
                    if (res.code != 0)
                        throw new Error(res.message);
                    this.setState({
                        message: {
                            text: TextMeasurements.en.common.success_share_test,
                            code: Constants.ALERT_CODE_SUCCESS
                        }
                    });
                }).catch(err => {
                    if (err.isCanceled)
                        return;
    
                    this.setState({
                        message: {
                            text: err.message,
                            code: Constants.ALERT_CODE_ERROR
                        }
                    })
                });
    
                this.promiseShareByEmail = promiseShareByEmail;
    

    this.props.requestShareByEmail(obj.email, obj.url) that function returns promise from axios.

    when component will unmount cancel function should be invoked.

    componentWillUnmount() {
            this.promiseShareByEmail.cancel();
        }
    

    enjoy.

    0 讨论(0)
提交回复
热议问题