gokiller
V2EX  ›  React

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

  •  1
     
  •   gokiller · Feb 3, 2024 · 3359 views
    This topic created in 1013 days ago, the information mentioned may be changed or developed.

    在看一本 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 replies  •  2024-02-03 12:34:44 +08:00
    likaci
    likaci
    Feb 3, 2024
    1
    组件销毁时会执行, strict 模式下也会执行一次...
    estk
    estk
    Feb 3, 2024 via iPhone
    2
    你实测的结果是怎样的?
    xling
    xling
    Feb 3, 2024❤️1
    4
    你的组件没销毁
    zhw2590582
    zhw2590582
    Feb 3, 2024
    5
    useEffect 真是让人疑惑,写久了 react 也会遇到一些意向不大的情况
    leaflxh
    leaflxh
    Feb 3, 2024
    6
    对于初学者写 class 组件或者能更好理解,但是现在已经过时了 ,只推荐用 hook
    gokiller
    gokiller
    OP
    Feb 3, 2024
    7
    @xling 对,知道问题所在了,感谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3957 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 09:41 · PVG 17:41 · LAX 01:41 · JFK 04:41
    ♥ Do have faith in what you're doing.