使用React 16.8.6(在之前的版本16.8.3上很好),当我试图阻止fetch请求上的无限循环时,我得到了这个错误:

./src/components/BusinessesList.js
Line 51:  React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array  react-hooks/exhaustive-deps

我一直无法找到一个解决办法来停止这个无限循环。我想远离使用useReducer()。我确实找到了关于'筋疲力尽-deps' lint规则#14920的讨论[ESLint]反馈,其中一个可能的解决方案是,如果你认为你知道你在做什么,你可以总是// ESLint - disabled -next-line react-hooks/详尽-deps。我对我正在做的事情没有信心,所以我还没有尝试实现它。

我有这个当前的设置,React钩子useEffect连续运行永远/无限循环,唯一的评论是关于useCallback(),我不熟悉。

我目前如何使用useEffect()(我只想在开始时运行一次,类似componentDidMount()):

useEffect(() => {
    fetchBusinesses();
  }, []);
const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };

当前回答

好吧,如果你想从不同的角度来看这个问题,你只需要知道React有哪些非耗尽的选项。你不应该在效果中使用闭包函数的原因之一是在每次渲染时,它都会被重新创建/销毁。

因此,钩子中有多个React方法被认为是稳定的和非耗尽的,在这些方法中,您不必应用到useEffect依赖项,并且反过来也不会破坏React -hooks/竭-deps的约定规则。例如,useReducer或useState的第二个返回变量是一个函数。

const [,dispatch] = useReducer(reducer, {});

useEffect(() => {
    dispatch(); // Non-exhausted - ESLint won't nag about this
}, []);

所以反过来,你可以让所有的外部依赖关系与你在reducer函数中的当前依赖关系共存。

const [,dispatch] = useReducer((current, update) => {
    const { foobar } = update;
    // Logic

    return { ...current, ...update };
}), {});

const [foobar, setFoobar] = useState(false);

useEffect(() => {
    dispatch({ foobar }); // non-exhausted `dispatch` function
}, [foobar]);

其他回答

您可以删除第二个参数类型数组[],但fetchBusinesses()也将在每次更新时被调用。如果愿意,可以在fetchBusinesses()实现中添加IF语句。

React.useEffect(() => {
  fetchBusinesses();
});

另一个方法是在组件外部实现fetchBusinesses()函数。如果有的话,不要忘记将任何依赖参数传递给fetchBusinesses(依赖项)调用。

function fetchBusinesses (fetch) {
  return fetch("theURL", { method: "GET" })
    .then(res => normalizeResponseErrors(res))
    .then(res => res.json())
    .then(rcvdBusinesses => {
      // some stuff
    })
    .catch(err => {
      // some error handling
    });
}

function YourComponent (props) {
  const { fetch } = props;

  React.useEffect(() => {
    fetchBusinesses(fetch);
  }, [fetch]);

  // ...
}

如果您想禁用这个无用的消息,只需在文件的开头添加这个。

/* eslint-disable react-hooks/exhaustive-deps */

这将禁用整个文件的警告。

const [mount, setMount] = useState(false)
const fetchBusinesses = () => {
   // Function definition
}
useEffect(() => {
   if(!mount) {
      setMount(true);
      fetchBusinesses();
   }
},[fetchBusinesses, mount]);

这个解决方案非常简单,你不需要重写ESLint警告。只需维护一个标志,以检查组件是否已挂载。

你可以这样尝试:

const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"})
        .then(res => normalizeResponseErrors(res))
        .then(res => {
            return res.json();
        })
        .then(rcvdBusinesses => {
            // Some stuff
        })
        .catch(err => {
            // Some error handling
        });
  };

and

useEffect(() => {
    fetchBusinesses();
});

这对你有用。

但我的建议是试试这种方法,它也适用于你。 这比以前的方法好。我是这样用的:

useEffect(() => {
    const fetchBusinesses = () => {
        return fetch("theURL", {method: "GET"})
            .then(res => normalizeResponseErrors(res))
            .then(res => {
                return res.json();
            })
            .then(rcvdBusinesses => {
                // Some stuff
            })
            .catch(err => {
                // Some error handling
            });
    };

    fetchBusinesses();
}, []);

如果您根据特定的id获取数据,则在回调中添加useEffect [id]。然后它就不能显示警告 React钩子useEffect有一个缺失的依赖:'any thing'。要么包含它,要么删除依赖数组

好吧,如果你想从不同的角度来看这个问题,你只需要知道React有哪些非耗尽的选项。你不应该在效果中使用闭包函数的原因之一是在每次渲染时,它都会被重新创建/销毁。

因此,钩子中有多个React方法被认为是稳定的和非耗尽的,在这些方法中,您不必应用到useEffect依赖项,并且反过来也不会破坏React -hooks/竭-deps的约定规则。例如,useReducer或useState的第二个返回变量是一个函数。

const [,dispatch] = useReducer(reducer, {});

useEffect(() => {
    dispatch(); // Non-exhausted - ESLint won't nag about this
}, []);

所以反过来,你可以让所有的外部依赖关系与你在reducer函数中的当前依赖关系共存。

const [,dispatch] = useReducer((current, update) => {
    const { foobar } = update;
    // Logic

    return { ...current, ...update };
}), {});

const [foobar, setFoobar] = useState(false);

useEffect(() => {
    dispatch({ foobar }); // non-exhausted `dispatch` function
}, [foobar]);