何时在组件中使用效果触发将卸载



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

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

可选地,第二个参数也可以只是一个空数组,在 在这种情况下,它只会在componentDidMountcomponentWillUnmount,效果不会在componentDidUpdate上运行。

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

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

例如,您可以获得上述效果,例如

useEffect(() => {
  API.getUser(userId);
  return () => {
      // cancel api here
  }
}, [userId]);

所以在上面的例子中,useEffect 返回的匿名函数将在效果第二次运行之前(在 userId 更改时发生(或卸载时

调用

你可以从useEffect返回清理函数,该函数将在卸载之前运行

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
  };
}, []);

最新更新