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

查看:95
本文介绍了具有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清理 来获取最新版本的道具?

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,您的效果不依赖于道具或状态的任何值,因此它不需要重新运行.

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并将要使用的道具存储在闭包中,例如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天全站免登陆