[英]React useEffect depedencies warning eslint
I'm trying to run a function inside useEffect,My code was work perfectly but I got a warning from eslint.我正在尝试在 useEffect 中运行 function,我的代码运行良好,但我收到了来自 eslint 的警告。
const {
error: { setErrorHolder },
} = useNotification();
useEffect(() => {
if (process.env.NODE_ENV === "production") {
setErrorHolder({ statusCode: 404, isAppError: true });
}
}, []);
In this example, I use the ReactQuery library for fetching.在此示例中,我使用 ReactQuery 库进行抓取。
const { refetch } = useQuery('example');
useEffect(() => {
refetch();
}, []);
Is there a better solution for this case?这种情况有更好的解决方案吗? Thank you.
谢谢你。
You call refetch inside useEffect.您在 useEffect 中调用 refetch。 That causes eslint (Rule of hooks) raises the issue since eslint doesn't know that "refetch" is never change.
这会导致 eslint(钩子规则)引发问题,因为 eslint 不知道“refetch”永远不会改变。
To fixed:固定:
useEffect(...your effect...,
// eslint-disable-next-line react-hooks/exhaustive-deps
[])
The solution is to add the dependency to the array you pass to useEffect.解决方案是将依赖项添加到传递给 useEffect 的数组中。
useEffect(() => {
if (process.env.NODE_ENV === "production") {
setErrorHolder({ statusCode: 404, isAppError: true });
}
}, [setErrorHolder]);
useEffect(() => {
refetch();
}, [refetch]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.