使用带有依赖项的 useEffect 钩子时,清理功能何时触发? [英] When is the cleanup function triggered when using useEffect hook with dependencies?

查看:28
本文介绍了使用带有依赖项的 useEffect 钩子时,清理功能何时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 useEffect 来显示 UI 加载...但仅在 250 毫秒之后.它有效......但我真的不明白为什么,特别是如何以及何时 useEffect 调用返回的函数(清除超时).

I'm using a useEffect to show a UI Loading... but only after 250ms. It works ... but I really don't understand why and specially how and when useEffect invokes the returned function (that clears the timeout).

嗯......我不确定这是否完美.有时应该会出现正在加载..."消息,但没有.

Well ... I'm not sure that's work perfectly. Sometimes the "Loading ..." message should appear but it's not.

 const [loadingAfterShortTime, setLoadingAfterShortTime] = useState(false);

 useEffect(() => {
  setLoadingAfterShortTime(bool => false);
  if (myDepandanceToTrigTheLoadingWord === true) {
    const id = setTimeout(() => {
      setLoadingAfterShortTime(bool => true);
    }, 250);
    return () => {
      clearTimeout(id);
    };
  }
}, [myDepandanceToTrigTheLoadingWord]);

推荐答案

@Powell Ye 提供的解释很好,但是在谈到重新渲染时(例如,当道具更改时)有一些错误的信息

The explanation provided by @Powell Ye is good however there a bit of erroneous information specifically when speaking about re-renders (e.g. when props change)

考虑一些具有以下内容的简单组件

consider some simple component with the following

    useEffect( () => {
        console.log('Effect is applied')
        //some logic
        return () => {
            console.log('cleaning up')
            //cleanup logic
        }
    })
    return (<>
        {console.log('rendering...')}
     </>)

说在你可能认为的变化中传递的道具

say the props passed in changes you might think it goes as such

  1. '清理'
  2. 新道具
  3. '正在渲染...'
  4. '应用效果'

然而,实际发生了以下情况

However, the following actually occurs

  1. 新道具
  2. '正在渲染...'
  3. '清理'
  4. '应用效果'

也就是说,清理功能在AFTER新渲染/绘制但BEFORE应用新"效果后运行,docs 对此可能有点含糊

That is, the clean up function runs AFTER the new render/painting but BEFORE the 'new' effects are applied, the docs can be a bit ambigious about this

在执行下一个效果之前先清理上一个效果

the previous effect is cleaned up before executing the next effect

这样做是出于性能原因 => 以便渲染不会延迟(有时对我来说也很令人沮丧)

This is done for performance reasons => so that rendering is not delayed ( it can be frustrating at times for me too )

这篇关于使用带有依赖项的 useEffect 钩子时,清理功能何时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆