小编典典

使用useEffect React Hook时如何解决缺少依赖项警告?

reactjs

使用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.我不确定自己在做什么,所以我还没有尝试实现它。

我有这个当前设置,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
      });
  };

阅读 6664

收藏
2020-07-22

共1个答案

小编典典

如果除了效果以外没有在其他地方使用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,则必须注意两点

  1. 有没有与你的任何问题, 传递fetchBusinesses当它与它的外围封闭件支架中的二手的方法是什么?
  2. 您的方法是否依赖于从其封闭包中收到的一些变量?事实并非如此。
  3. 在每个渲染上,都会重新创建fetchBusinesses,因此将其传递给useEffect会引起问题。因此,如果要将fetchBusinesses传递给依赖项数组,则必须记住它。

综上所述,我想说的是,如果您在fetchBusinesses外部使用,则可以使用useEffect禁用规则,// eslint-disable- next-line react-hooks/exhaustive-deps否则可以将方法移到useEffect内部

要禁用该规则,您可以这样写

useEffect(() => {
   // other code
   ...

   // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
2020-07-22