小编典典

具有React useEffect钩子的componentWillUnmount

reactjs

如何能在useEffect钩(或任何其他挂钩的这个问题)可以被用来复制componentWillUnmount

在传统的类组件中,我将执行以下操作:

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捕获安装过程中的道具,而不会在卸载过程中捕获道具的状态。

我怎么能获得最新版本的道具的useEffect清理 ,而不 在每一个道具的变化运行的函数体(或清理)?
\

反应文档状态:

如果要运行效果并仅将其清除一次(在挂载和卸载时),则可以传递一个空数组([])作为第二个参数。这告诉React您的效果不依赖于props或state的任何值,因此它不需要重新运行。

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


阅读 368

收藏
2020-07-22

共1个答案

小编典典

您可以使用useRef并存储要在闭包内使用的道具,例如render useEffect返回回调方法

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以便在所需道具的任何更改时进行清理和初始化

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