且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用useEffect React Hook时如何修复缺少的依赖警告

更新时间:2022-06-12 22:19:46

如果你没有在效果之外的任何地方使用 fetchBusinesses 方法,你可以简单地将它移动到效果中并避免警告

If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning

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,则必须注意两件事

If however you are using fetchBusinesses outside of render, you must note two things

  1. fetchBusinesses 在带有封闭闭包的挂载期间使用时,您没有将它作为方法传递有什么问题吗?
  2. 您的方法是否依赖于从其封闭闭包中接收到的某些变量?对您而言,情况并非如此.
  3. 在每次渲染时,都将重新创建 fetchBusinesses,因此将其传递给 useEffect 会导致问题.因此,如果要将 fetchBusinesses 传递给依赖项数组,则首先必须记住它.
  1. Is there any issue with you not passing fetchBusinesses as a method when it's used during mount with its enclosing closure?
  2. Does your method depend on some variables which it receives from its enclosing closure? This is not the case for you.
  3. On every render, fetchBusinesses will be re-created and hence passing it to useEffect will cause issues. So first you must memoize fetchBusinesses if you were to pass it to the dependency array.

总而言之,如果您在 useEffect 之外使用 fetchBusinesses,您可以使用 //eslint-disable-next- 禁用规则线 react-hooks/exhaustive-deps 否则你可以移动 useEffect 内的方法

To sum it up I would say that if you are using fetchBusinesses outside of useEffect you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps otherwise you can move the method inside of useEffect

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

To disable the rule you would write it like

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

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