javascript - 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
在组件安装时放置一个,并在它卸载时清除它.. :(
解决方案
尝试这个:
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]);
推荐阅读
- ruby-on-rails - session#destroy 未应用
- c++ - Visual C++ static initializer strange behavior
- java - Spring的两种文档
- go - How to access request headers in grpc service proxied by. grpc-gateway in golang
- angular - Disable button using input textbox id
- python-3.x - 合并熊猫数据框时出现KeyError:名称:TimeStamp,dtype:datetime64 [ns]
- pnpm - 如何以编程方式使用 pnpm / supi 安装软件包?
- flutter - 如何在一行内有多个(4)列(或类似的)与 ListView.builder 一起滚动
- docker - Docker 覆盖文件夹吃掉了 GB 的数据
- ember.js - Ember - Component property is not getting updated in template hbs