IT常识
技术 Python PHP JavaScript IOS Android Java 数据库 资源 公众号 代码片段 github
  • IT常识
  • 技术

React + antd 组件离开页面以后出现Can only update a mounted or mounting component 的解决办法

Posted 2020-10-03 纸鸢@tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React + antd 组件离开页面以后出现Can only update a mounted or mounting component 的解决办法相关的知识,希望对你有一定的参考价值。

     做项目的过程中,来回切换页面时,一直遇到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 的解决办法的主要内容,如果未能解决你的问题,请参考以下文章

(c)2006-2024 SYSTEM All Rights Reserved IT常识