简体   繁体   English

为什么 useEffect 在 window.innerWidth 发生变化时运行,即使其中的第二个参数是空数组

[英]why does useEffect run once the window.innerWidth changes even though the second param in it is an empty array

useEffect in this code runs every time the window size changes, but the second parameter in useEffect is an empty array, I thought as long as the second parameter doesn't change compare to last time, the useEffect won't run这段代码中的useEffect每次window大小变化时都会运行,但是useEffect中的第二个参数是一个空数组,我认为只要第二个参数与上次相比没有变化, useEffect就不会运行

 import React from "react" export default function WindowTracker() { const [windowWidth, setWindowWidth] = React.useState(window.innerWidth) React.useEffect(() => { window.addEventListener("resize", function() { setWindowWidth(window.innerWidth) }) }, []) return ( <h1>Window width: {windowWidth}</h1> ) }

It is not that useEffect runs, rather the registered event listener.不是useEffect运行,而是注册的事件监听器。 useEffect indeed runs once and registers the event listener once. useEffect确实运行一次并注册一次事件侦听器。 But then afterwards, the listener callback is called.但随后,调用了侦听器回调。

If you console.log inside of useEffect, you will see it will actually gets run only once.如果你在 useEffect 中使用 console.log,你会看到它实际上只会运行一次。 Basically you have set once the event listener for the resize event.基本上,您已经为 resize 事件设置了一次事件侦听器。 But you still have the registered event listener in place, which works as it's supposed to.但是您仍然拥有已注册的事件侦听器,它按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM