如何在反应 useLayoutEffect 内去抖动?

时间:2021-01-30 18:02:22

标签: reactjs

当用户调整窗口大小时,宽度应每 1000 毫秒设置一次。我尝试使用 lodash 去抖动,但不知何故它没有被触发或延迟触发。我需要如何更改代码?

我的代码: Sandbox

const Viewport = () => {
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    const handleWindowResize = () => {
      debounce(() => {
        const windowWidth = window.innerWidth;

        setWidth(windowWidth);
        console.log("windowWidth", windowWidth);
      }, 1000);
    };

    window.addEventListener("resize", handleWindowResize);
    handleWindowResize();
    return () => window.removeEventListener("resize", handleWindowResize);
  }, []);

  return <div>Window width: {width}</div>;
};

export default Viewport;

1 个答案:

答案 0 :(得分:2)

您不需要将 debounce 函数包装在另一个函数中

  useLayoutEffect(() => {
    const handleWindowResize = debounce(() => {
      const windowWidth = window.innerWidth;
      setWidth(windowWidth);
    }, 1000);

    window.addEventListener("resize", handleWindowResize);
    handleWindowResize();
    return () => window.removeEventListener("resize", handleWindowResize);
  }, []);

debounce 已经返回另一个函数,您可以直接将其传递给事件侦听器。