react相關小技巧

1、咱們在項目中切換路由的時候可能會遇到react

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.

關於react中切換路由時報以上錯誤,實際的緣由是由於在組件掛載(mounted)以後進行了異步操做,好比ajax請求或者設置了定時器等,而你在callback中進行了setState操做。當你切換路由時,組件已經被卸載(unmounted)了,此時異步操做中callback還在執行,所以setState沒有獲得值。
最簡單也是最有效的方法
componentWillUnmount = () => {
    this.setState = (state,callback)=>{
      return;
    };
}
相關文章
相關標籤/搜索