React篇-报错信息:warning: Can't call setState (or forceUpdate) on an unmounted component.

本文针对React应用中常见的一种错误——组件卸载后尝试调用setState导致的警告,提供了一种解决方案。通过引入一个标记变量isMounted,并在组件的生命周期方法componentDidMount和componentWillUnmount中对其进行更新,确保了setState操作只在组件挂载时有效。

报错信息是:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

 

 

 

项目中tab切换,内容封装成来一个子组件,在跳转到别的路由页面,然后再返回该页面点击tab切换的时候报上述错误,找了很久的原因,目前得到的分析应该是,在路由跳转过来的时候子组件还未加载到,此时点击切换tab栏(这里需要setState),就会报上述的错误,解决办法如下:

 

设置变量 let isMounted = false

 

然后在componentDidMount周期设置:

componentDidMount(){
isMounted = true;
}
  
在componentWillUnmount周期设置:
componentWillUnmount(){
isMounted = false
}

组件render这里判断isMounted的值:
{
                        isMounted && this.state.activeIndex === 1 && <div className="tabC01">
                                                            <FTab tabCon={'tabCon01'}/>
                                                        </div>
}

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/keleyz/p/9509634.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值