使用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
      });
  };

当前回答

本文是关于使用钩子获取数据的很好的入门读物:https://www.robinwieruch.de/react-hooks-fetch-data/

本质上,在useEffect中包含fetch函数定义:

useEffect(() => {
  const fetchBusinesses = () => {
    return fetch("theUrl"...
      // ...your fetch implementation
    );
  }

  fetchBusinesses();
}, []);

其他回答

您可以删除第二个参数类型数组[],但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]);

  // ...
}

本文是关于使用钩子获取数据的很好的入门读物:https://www.robinwieruch.de/react-hooks-fetch-data/

本质上,在useEffect中包含fetch函数定义:

useEffect(() => {
  const fetchBusinesses = () => {
    return fetch("theUrl"...
      // ...your fetch implementation
    );
  }

  fetchBusinesses();
}, []);

实际上,在使用钩子进行开发时,警告非常有用。但在某些情况下,它会刺痛你。特别是当您不需要监听依赖项更改时。

如果你不想将fetchBusinesses放在钩子的依赖项中,你可以简单地将它作为参数传递给钩子的回调函数,并将fetchBusinesses设置为它的默认值,如下所示:

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

这不是最佳实践,但在某些情况下可能有用。

同样,正如Shubham所写的,你可以添加下面的代码来告诉ESLint忽略钩子的检查。

// eslint-disable-next-line react-hooks/exhaustive-deps

这不是一个特定于问题用例的答案,而是更普遍的情况,并涵盖了useEffect或提取和导入不工作的情况。 useRef senario:

有时情况是,useEffect应该有一个空数组,你仍然想在useEffect部分的状态中使用,但仍然不想将它们作为依赖注入,你也可以尝试useCallback,现在react抱怨useCallback的依赖,你卡住了。 在这种情况下,在某些情况下可以使用useRef。例如:

const locationRef = useRef(location);
useEffect(()=>{
const qs = locationRef.current.search
...
},[])

在使用这种技术时,您应该小心,并注意useRef不会激活渲染进程。

似乎在组件中声明了fetchBusinesses函数。 这意味着在每次渲染中,它都声明了触发钩子的新函数。

有两种方法可以解决这个问题。

将fetchBusinesses函数声明移出组件。 使用useCallback钩子包装fetchBusinesses函数。

第一种选择更可取。