繁体   English   中英

安装时调用 useEffect clean up

[英]useEffect clean up being called on mounting

我有一个功能组件

export default function Comp(props){
  .
  .
  .
  useEffect(() => {
    return () => {// cleanup
      console.log("Called!")
    }
  }, [...dependiences])

}

我有另一个按钮可以安装和卸载组件

出于某种原因,在安装组件时会调用清理 function

我可以看到控制台日志

如何防止这种情况发生并仅在组件卸载时才调用清理

父级创建这样的组件

  
export default function Comp(props){
  .
  .
  .
  const [mount, setMount] = useState(false);

  return <> {mount && <Child {...someProps}/>}</>

}

如果您使用React 18并且您的应用程序包含在<StrictMode>标记中,那么这是有意添加的预期行为,希望帮助开发人员捕获与其组件生命周期相关的错误,例如滥用/误用useEffect钩。

新的StrictMode实际上所做的是卸载并在渲染后重新安装每个组件。

导致初始生命周期如下所示:

* React mounts the component.
  * Layout effects are created.
  * Effects are created.
* React simulates unmounting the component.
  * Layout effects are destroyed.
  * Effects are destroyed.
* React simulates mounting the component with the previous state.
  * Layout effects are created.
  * Effects are created.

请注意,它仅在开发环境中以这种方式运行,而不是在生产构建中。

参考: https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM