使用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()。我确实在https://github.com/facebook/react/issues/14920找到了这个讨论,在这里可能的解决方案是You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing.我不确定自己在做什么,所以我还没有尝试实现它。
useReducer()
You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing.
我有这个当前设置,React钩子useEffect永远/无限循环连续运行,唯一的注释是useCallback()我不熟悉的。
useCallback()
我目前的使用方式useEffect()(类似于,我一开始只想运行一次componentDidMount())
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 }); };
如果除了效果以外没有在其他地方使用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(); }, []);
但是,如果在渲染之外使用fetchBusinesses,则必须注意两点
fetchBusinesses
综上所述,我想说的是,如果您在fetchBusinesses外部使用,则可以使用useEffect禁用规则,// eslint-disable- next-line react-hooks/exhaustive-deps否则可以将方法移到useEffect内部
useEffect
// eslint-disable- next-line react-hooks/exhaustive-deps
要禁用该规则,您可以这样写
useEffect(() => { // other code ... // eslint-disable-next-line react-hooks/exhaustive-deps }, [])