Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how?

问题原因:

我们经常需要在异步操作中更新state状态值,通过更新state状态值变化来实现界面内容显示的更新,有时候异步操作执行完成更新state状态,但是用户已经返回上一界面,当前页面已经销毁就会出现上面的错误;

解决办法:

1.定义isMount变量标识当前组件的状态;

    constructor(props){
        super(props);
        this._isMounted = false;
    }

2.在componentDidMount()中更新变量状态,标识页面加载完成

     componentDidMount() {
        this._isMounted = true;
    }

3.在组件销毁之间更新变量状态,标识界面已经销毁

    componentWillUnmount() {
        this._isMounted = false;
    }

   

4.异步回调执行时检测页面组件是否销毁,未销毁继续执行

 executionDataParsing(){
        const _this = this;
        //执行数据解析和回调
        this.completeCommand[this.currentCommandIndex].dataParsing(function(data){
            _this._isMounted && _this.showData(data);
        });
    }

    子类覆盖执行数据显示
    showData(data){

    }

 

参考:

https://stackoverflow.com/questions/52061476/cancel-all-subscriptions-and-asyncs-in-the-componentwillunmount-method-how

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值