如何在组件卸载时使用 useEffect 挂钩来有条件地运行代码

Mic*_*ael 4 reactjs react-hooks

由于某些奇怪的原因,我的“卸载”useEffect 挂钩中的 props 值始终处于原始状态(true),我可以在开发工具中进行控制台并看到它已更改为 false,但是当在卸载时调用 useEffect 时,它始终处于原始状态真的。
我尝试将道具添加到依赖项中,但随后不再仅在卸载时调用它,并且无法达到其目的。
编辑:我知道依赖项数组是空的,我不能在每次更改时触发它,它只需要在使用道具中的更新值卸载时触发。这可能吗?

React.useEffect(() => {
    return () => {
      if (report.data.draft) { // this is ALWAYS true
        report.snapshot.ref.delete();
      }
    };
  }, []);

Run Code Online (Sandbox Code Playgroud)

如何在卸载时有条件地运行代码,条件取决于更新的 props 状态?

Nic*_*wer 5

如果您希望代码仅在卸载时运行,则需要使用空依赖项数组。如果您还需要来自闭包的数据,这些数据可能在组件首次渲染和最后一次渲染之间发生变化,则需要使用 a 来ref在卸载发生时使该数据可用。例如:

const onUnmount = React.useRef();
onUnmount.current = () => {
  if (report.data.draft) {
    report.snapshot.ref.delete();
  }
}
React.useEffect(() => {
  return () => onUnmount.current();
}, []);
Run Code Online (Sandbox Code Playgroud)

如果您经常这样做,您可能需要将其提取到自定义挂钩中:

export const useUnmount = (fn): => {
  const fnRef = useRef(fn);
  fnRef.current = fn;

  useEffect(() => () => fnRef.current(), []);
};


// used like:
useUnmount(() => {
  if (report.data.draft) {
    report.snapshot.ref.delete();
  }
});
Run Code Online (Sandbox Code Playgroud)