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
}

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