简体   繁体   English

返回的 function 如何不破坏 useEffect 中的事件监听器?

[英]How the returned function is not destroying event listener in useEffect?

I made this custom hook to get window width.我做了这个自定义挂钩以获得 window 宽度。 It is working but I have a question.它正在工作,但我有一个问题。 I used useEffect to add event listener to window at component mount.我使用useEffect在组件挂载时将事件侦听器添加到window But then my friend suggested me to use return function to remove the event listener.但后来我的朋友建议我使用return function 来删除事件监听器。 How this is working?这是怎么回事? Shouldn't the returned function destroy the event listener and make it not work?返回的 function 不应该破坏事件侦听器并使其不起作用吗? Since this is happing one time on component mount?因为这是在组件安装上发生的一次?

import React from "react";

const useWindowSize = () => {
  const [windowSize, setWindowSize] = React.useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const windowResize = () => {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
  };
  React.useEffect(() => {
    window.addEventListener("resize", windowResize);
    return () => {
      window.removeEventListener("resize", windowResize);
    };
  }, []);
  return windowSize;
};

export default useWindowSize;

The returned function inside the useEffect gets executed just before your component gets unmounted. useEffect 中返回的useEffect在您的组件被卸载之前执行。 It is not executed on mount.它不在挂载时执行。

Without this returned function, every time your component re-renders, if you hadn't that empty array dependency, and when it gets unmounted and mounted, a new EventListener is added in memory (which is bad).如果没有返回 function,每次您的组件重新呈现时,如果您没有那个空数组依赖项,并且当它被卸载和安装时,就会在 memory 中添加一个新的EventListener (这很糟糕)。

This callback in return of useEffect is called on unmount .unmount上调用此回调以返回useEffect Which means that eventListener is removed when your component is no longer rendered, or when its "remounted" (key prop was changed).这意味着当您的组件不再呈现时,或者当它的“重新安装”(关键道具已更改)时,将删除 eventListener。 This is important because without removing event listener, there will be several same eventListeners hooked at the same time.这很重要,因为如果不删除事件侦听器,将同时挂接多个相同的事件侦听器。

shouldn't return function destroy event listener and make it not work?不应该返回 function 销毁事件侦听器并使其不起作用? since this is happing one time on component mount?因为这是在组件安装上发生的一次?

The return function will be executed in your case when the component using the hook unmounts (because of empty array as dependencies).返回 function 将在您的情况下执行,当使用挂钩的组件卸载时(因为空数组作为依赖项)。 So at that time it makes sense to unregister the listener I suppose.所以在那个时候注销我想的听众是有意义的。 Morereading .读书

try code:尝试代码:

    const windowResize = useCallback(event => {
        setWindowSize({
            width: window.innerWidth,
            height: window.innerHeight,
        });
    }, []);

    useEffect(() => {
        window.addEventListener("keydown", windowResize);
        return () => {
            window.removeEventListener("keydown", windowResize);
        };
    }, [windowResize]);

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

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