1. 程式人生 > >React + antd 組件離開頁面以後出現Can only update a mounted or mounting component 的解決辦法

React + antd 組件離開頁面以後出現Can only update a mounted or mounting component 的解決辦法

建議 react set scrip log 卸載 str class ()

做項目的過程中,來回切換頁面時,一直遇到Can only update a mounted or mounting component 這個問題,原因是當離開頁面以後,組件已經被卸載,執行setState時無法找到渲染組件。

解決辦法特別簡單,在離開頁面時的周期函數(componentWillUnmount)中:

  //組件將被卸載  
  componentWillUnmount(){ 
        //重寫組件的setState方法,直接返回空
        this.setState = (state,callback)=>{
          return;
        };  
    }

再來回切換頁面以後,只要頁面離開就會執行該方法,當頁面再次進入時又會重新掛載父組件的setState方法,從而不影響頁面的渲染。

不過該方法不是很嚴謹,在集成的子組件中能修改父組件的setState方法,不過在javascript的語法中很適用,建議只在出現上述bug的頁面中使用。

React + antd 組件離開頁面以後出現Can only update a mounted or mounting component 的解決辦法