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模塊javascript
import *as React from 'react' const SafeSetState = function<P extends object>(WrappedComponent:React.ComponentClass<P>) { 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了java
其實還有其餘高階解決辦法,能夠參考這個大神的文章從一次react異步setState引起的思考react