React Hook useEffect 缺少对 setInterval 的依赖(GatsbyJs)

React Hook useEffect has a missing dependency (GatsbyJs) with setInterval

我的组件中有一个旋转木马,我想在组件安装时独立滑动, 所以我使用 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,并在卸载时清除它。:(

试试这个:

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]);