V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gokiller
V2EX  ›  React

下面这个 react 的 useeffect 代码中的 return 卸载,清理函数为什么不运行

  •  1
     
  •   gokiller · 84 天前 · 1451 次点击
    这是一个创建于 84 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在看一本 react 书时,它是这么写的。

    function App1(){
      const handleWindowsResize=()=>{
        console.log('windows size change')
      }
    
    
      useEffect(()=>{
        console.log('called')
        const timerObj = setInterval(()=>{
          console.log('每秒+1')
        },1000)
    
        window.addEventListener('resize',handleWindowsResize)
    
        return ()=>{
          console.log('clear')
          clearInterval(timerObj)
          window.removeEventListener('resize',handleWindowsResize)
        }
      },[])
    
    
      return (
        <div>
          Hello world
        </div>
      )
    }
    

    console 里面会定时输出 windows size change ,而不会进入到 useEffect 里面清除定时器。 根据对书中理解,return 函数是在第二次执行 useEffect 之前执行的? 而上面的 useEffect 只会执行一次,是不是意味者 return 函数里面的代码不会被执行?

    7 条回复    2024-02-03 12:34:44 +08:00
    likaci
        1
    likaci  
       84 天前
    组件销毁时会执行, strict 模式下也会执行一次...
    estk
        2
    estk  
       84 天前 via iPhone
    你实测的结果是怎样的?
    xling
        4
    xling  
       84 天前   ❤️ 1
    你的组件没销毁
    zhw2590582
        5
    zhw2590582  
       84 天前
    useEffect 真是让人疑惑,写久了 react 也会遇到一些意向不大的情况
    leaflxh
        6
    leaflxh  
       84 天前
    对于初学者写 class 组件或者能更好理解,但是现在已经过时了 ,只推荐用 hook
    gokiller
        7
    gokiller  
    OP
       84 天前
    @xling 对,知道问题所在了,感谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1523 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:53 · PVG 00:53 · LAX 09:53 · JFK 12:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.