useEffect 什么时候在 componentWillUnmount 中触发?

when does useEffect fire in componentWillUnmount?

我在博客中看到下面的声明,它是这样说的

useEffect(() => {
  API.getUser(userId);
}, [userId]);

Optionally the second parameter can also just be an empty array, in this case it will only execute on componentDidMount and componentWillUnmount and the effect won't run on componentDidUpdate.

卸载组件 (componentWillUnmount) 时是否执行了 API.getUser?据我所知 componentWillUnmount 当你从页面 A 转到页面 B 时触发。我现在很困惑,对我来说,上面的代码就像 componentDidMount,因为 userId 将从 undefinedid 一次。

您可以return 清除 useEffect 中的函数,它将 运行 在 unMount

之前
useEffect(() => {
  const subscription = props.source.subscribe(); // this will fire at after did Mount/ didUpdate
  return () => {
    // Clean up the subscription
    subscription.unsubscribe(); // this will afire at willUnmount
  };
});

如果将空数组作为第二个参数传递。

useEffect(() => {
  const subscription = props.source.subscribe(); // this run only after first rnede i.e componentDidmount
  return () => {
    // Clean up the subscription
    subscription.unsubscribe(); // this will afire at willUnmount ie componentWillUnmount
  };
}, []);

你对措辞有点困惑,当你传递一个空数组时,它不是在卸载时执行的效果,而是清理函数,它是将要执行的 useEffect 中返回的函数。

例如你可以像

一样有上面的效果
useEffect(() => {
  API.getUser(userId);
  return () => {
      // cancel api here
  }
}, [userId]);

所以在上面的例子中,useEffect返回的匿名函数会在effect第二次运行之前(当userId改变时)或者unmount