安装时调用 useEffect 清理

Ahm*_*fer 3 javascript unmount reactjs react-hooks

我有一个功能组件react版本是17

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

}

Run Code Online (Sandbox Code Playgroud)

我有另一个用于安装和卸载组件的按钮

由于某种原因,在安装组件时调用清理函数

我可以看到控制台日志

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

父级创建组件是这样的

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

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

}

Run Code Online (Sandbox Code Playgroud)

tom*_*leb 6

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

newStrictMode实际上所做的是卸载每个组件,然后在渲染后重新安装它。

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

* 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.
Run Code Online (Sandbox Code Playgroud)

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

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