简体   繁体   English

反应 useEffect depedencies 警告 eslint

[英]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:固定:

  • simply, add refetch to dependencies array as the suggestion简单地说,将 refetch 添加到 dependencies 数组作为建议
  • if you're sure that "refetch" is never change source, just disable eslint rule using the syntax如果您确定“refetch”永远不会更改源,只需使用语法禁用 eslint 规则
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM