React 警告和異常整理

Warning: Encountered two children with the same key


Warning: Encountered two children with the same key, `.$/base`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

children with the same key, .$/base 有兩個組件的key重複了
組件的key應該唯一的,方便組件在更新的時候找到對應的組件.

解決方案:
在當前頁面查找key 保證key的唯一性 

Can’t call setState (or forceUpdate) on an unmounted component


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.

不能在已經被銷燬的組件中調用setState()方案
出現場景:跳轉路由 當前組件被銷燬 組件內部還存在異步操作對state的狀態信息 比如http請求,定時器setTimeOut更新state

思路就是在組件卸載之前 控制異步不進行setState
解決方案一:組件被銷燬之前重寫setState方法 不對狀態做任何改變
componentWillUnmount(){
      this.setState = (state,callback)=>{
      return;
    };
    }
解決方案二:組件被銷燬之前 可以setState 銷燬之後就不能setState
    componentWillMount() {
        this._isMounted = true
        fetch('網絡請求').then (status, response)=>{
          if (this._isMounted) {
            this.setState({
                activityTipsImg: response.data.tips_url,
                activityTipsContent: response.data.tips_content
            })
          }
        });
}
componentWillUnmount() {
        this._isMounted = false
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章