React-native中页面卸载后setState出现警告的解决办法

1.在使用react-native开发时经常出现这个警告:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the xxx component
这个警告是因为出现在异步网络请求返回时页面已经卸载了,此时仍然会执行setState的代码导致的,有很多解决办法,一般就是加个isMount变量来判断是否卸载,但是这样挺麻烦的在每个页面都添加,我们可以用高阶组件来复用逻辑
2.我们可以定义一个ts模块

import *as React from 'react'
const SafeSetState = function

(WrappedComponent:React.ComponentClass

) { return class SafeComponent extends WrappedComponent{ private isMount:boolean componentDidMount(){ this.isMount=true if(super.componentDidMount){ super.componentDidMount() } } componentWillUnmount(){ this.isMount=false } setState(state,callback?){ if(this.isMount){ super.setState(state,callback) } } } }; export default SafeSetState

我们这种高阶组件方式叫反向继承,我们添加一个isMount属性,在setState时判断一下装填就OK了

其实还有其他高阶解决办法,可以参考这个大神的文章从一次react异步setState引发的思考

你可能感兴趣的:(react-native,javascript)