使用 React 16.8.6(在以前的版本 16.8.3 上很好),当我尝试防止获取请求上的无限循环时出现此错误:
./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()
。我确实找到了这个讨论 [ESLint] 对 ‘exhaustive-deps’ lint rule #14920 的反馈, 其中一个可能的解决方案是 You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing.
我对自己在做什么没有信心,所以我没有尝试实施它只是还没有。
我有这个当前设置, _ React hook 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
});
};
原文由 russ 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您没有在效果之外的任何地方使用 fetchBusinesses 方法,您可以简单地将其移动到效果中并避免警告
但是,如果您在渲染之外使用 fetchBusinesses,则必须注意两件事
fetchBusinesses
作为一种方法,是否有任何问题?总而言之,如果您在
fetchBusinesses
useEffect
您可以使用// eslint-disable-next-line react-hooks/exhaustive-deps
禁用规则,否则您可以将方法移到 useEf要禁用规则,您可以这样编写