带有 React useEffect 钩子的 componentWillUnmount [英] componentWillUnmount with React useEffect hook

查看:35
本文介绍了带有 React useEffect 钩子的 componentWillUnmount的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 useEffect 钩子(或任何其他与此相关的钩子)来复制 componentWillUnmount?

How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount?

在传统的类组件中,我会做这样的事情:

In a traditional class component I would do something like this:

class Effect extends React.PureComponent {
    componentDidMount() { console.log("MOUNT", this.props); }
    componentWillUnmount() { console.log("UNMOUNT", this.props); }
    render() { return null; }
}

使用 useEffect 钩子:

function Effect(props) {
  React.useEffect(() => {
    console.log("MOUNT", props);

    return () => console.log("UNMOUNT", props)
  }, []);

  return null;
}

(完整示例:https://codesandbox.io/s/2oo7zqzx1n)

这不起作用,因为 useEffect 中返回的cleanup"函数捕获了安装期间的道具,而不是卸载期间道具的状态.

This does not work, since the "cleanup" function returned in useEffect captures the props as they were during mount and not state of the props during unmount.

如何在 useEffect 清理中获取最新版本的 props 而不在每次 prop 更改时运行函数体(或清理)?

How could I get the latest version of the props in useEffect clean up without running the function body (or cleanup) on every prop change?

类似的问题没有解决访问权限的问题到最新的道具.

A similar question does not address the part of having access to the latest props.

react 文档 状态:

如果你想运行一个效果并且只清理一次(在挂载和卸载时),你可以传递一个空数组 ([]) 作为第二个参数.这告诉 React 你的 effect 不依赖于 props 或 state 的任何值,所以它永远不需要重新运行.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

但是在这种情况下,我依赖于道具...但仅用于清理部分...

In this case however I depend on the props... but only for the cleanup part...

推荐答案

你可以使用 useRef 并将要使用的 props 存储在一个闭包中,例如 render useEffect 返回回调方法

You can make use of useRef and store the props to be used within a closure such as render useEffect return callback method

function Home(props) {
  const val = React.useRef();
  React.useEffect(
    () => {
      val.current = props;
    },
    [props]
  );
  React.useEffect(() => {
    return () => {
      console.log(props, val.current);
    };
  }, []);
  return <div>Home</div>;
}

演示

然而,更好的方法是将第二个参数传递给 useEffect 以便清理和初始化发生在所需道具的任何更改

However a better way is to pass on the second argument to useEffect so that the cleanup and initialisation happens on any change of desired props

React.useEffect(() => {
  return () => {
    console.log(props.current);
  };
}, [props.current]);

这篇关于带有 React useEffect 钩子的 componentWillUnmount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆