首页 > 解决方案 > React Hook useEffect 缺少带有 setInterval 的依赖项(GatsbyJs)

问题描述

我的组件中有一个旋转木马,我想在组件安装时独立滑动,所以我使用useEffect()

useEffect(() => {
    const carouselTimer = setInterval(() => {
      setPage(true);
    }, 3000);
    return () => clearInterval(carouselTimer);
  }, []);

但是 Gatsby ESLintError 不断发出警告。

warn ESLintError: 
/home/damiisdandy/Projects/Xxxxx/Xxxxxx-client/src/components/Header/Carousel/Carousel.jsx
  59:6  warning  React Hook useEffect has a missing dependency: 'setPage'. Either include it or remove
the dependency array  react-hooks/exhaustive-deps

当我将 setPage 放在依赖数组中时,我收到另一个警告。

  23:9  warning  The 'setPage' function makes the dependencies of useEffect Hook (at line 59) change on
every render. To fix this, wrap the 'setPage' definition into its own useCallback() Hook

有关 setPage 函数的更多信息,就是这样。

const [currentPage, setCurrentPage] = useState(0);
  const [flowDirection, setFlowDirection] = useState(true);

  const setPage = (direction) => {
    if (direction) {
      setFlowDirection(true);
      setCurrentPage((currentPage) => {
        if (currentPage === pages.length - 1) {
          return 0;
        } else {
          return currentPage + 1;
        }
      });
    } else {
      setFlowDirection(false);
      setCurrentPage((currentPage) => {
        if (currentPage === 0) {
          return pages.length - 1;
        } else {
          return currentPage - 1;
        }
      });
    }
  };

我不知道如何处理这个警告(我讨厌在我的代码中看到警告),所以我该怎么做。我只想setInterval在组件安装时放置一个,并在它卸载时清除它.. :(

标签: javascriptreactjsgatsbyeslintreact-functional-component

解决方案


尝试这个:

const setPage = React.useCallback((direction) => {
  if (direction) {
    setFlowDirection(true);
    setCurrentPage((currentPage) => {
      if (currentPage === pages.length - 1) {
        return 0;
      } else {
        return currentPage + 1;
      }
    });
  } else {
    setFlowDirection(false);
    setCurrentPage((currentPage) => {
      if (currentPage === 0) {
        return pages.length - 1;
      } else {
        return currentPage - 1;
      }
    });
  }
}, [pages.length]);

推荐阅读