创建 React App + Contentful 无限请求循环

Create React App + Contentful infinite request loop

我开始学习以下教程: https://blog.logrocket.com/using-a-headless-cms-with-react/

不幸的是,当我完成它后,我注意到 chrome 中的 Network 选项卡在我导航到其中一个子项目后开始变得疯狂:

这是简化的代码版本:https://codesandbox.io/s/react-contentful-hx0de?from-embed

我想这一定是它是如何在这个片段中从 Contentful 调用的,它使用承诺来获得结果:

export default function useSinglePost(slug) {
  const promise = getSinglePost(slug);

  const [post, setPost] = useState(null);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    promise.then(result => {
      setPost(result[0].fields);
      setLoading(false);
    });
  }, [promise]);

  return [post, isLoading];
}

但我不明白为什么我会收到这种无限循环的网络请求。

尝试这样的事情,

export default function useSinglePost(slug) {
  const [post, setPost] = useState(null);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    getSinglePost(slug)
     .then(result => {
      setPost(result[0].fields);
      setLoading(false);
    });
  }, [slug]);

  return [post, isLoading];
}

const promise = getSinglePost(slug); 没有任何备忘录之类的。 因此,在 useEffect 中,当 promise 解析时,您会执行状态更改。导致重新渲染。在那些重新渲染的承诺上,重新定义更改 promise。再次导致 useEffect 到 运行。这再次导致状态改变和重新渲染,这是你的无限循环