【问题标题】:How to fix Error: Rendered more hooks than during the previous render when using SWR with useEffect如何修复错误:将 SWR 与 useEffect 结合使用时,渲染的钩子比上一次渲染时更多
【发布时间】:2022-01-09 19:09:18
【问题描述】:

我在使用带有 useEffect 挂钩的 SWR 时遇到问题。

我收到错误Rendered more hooks than during the previous render.

我的代码如下:

const { id } = router.query;
  const { data: recipe } = useRecipe(id);

  if (recipe) {
    useEffect(() => {
      if (typeof post.title === "string") {
        setTitle(recipe.title);
      }
    }, [recipe]);
  }

  if (!recipe) {
    return <div>Loading...</div>;
  }

useRecipe 是一个自定义的 SWR 钩子,它完美地工作,当我将 useEffect 注释掉数据加载时,如预期的那样。如果我将 useEffect 移到条件配方检查上方,我会得到配方未定义,如您所料。

我很想了解为什么我会收到错误“渲染的钩子比上一次渲染时更多”。

【问题讨论】:

标签: reactjs swr


【解决方案1】:

不要在循环、条件或嵌套函数中调用 Hooks。相反,请始终在 React 函数的顶层使用 Hooks。您可以在文档here

中阅读更多内容

在你的情况下,你可以这样做:

const { id } = router.query;
const { data: recipe } = useRecipe(id);

useEffect(() => {
  if (recipe && typeof post.title === "string") {
    setTitle(post.title);
  }
}, [recipe]);

if (!recipe) {
  return <div>Loading...</div>;
}

return ....;

【讨论】:

  • 感谢@Nir,感谢它,它运行良好。只是对于其他任何人来说,应该是 {data: recipe} = useRecipe 和 recipe.title。那是我的错误,我在最初的问题中写了帖子而不是食谱,为了清楚起见,我更新了最初的问题。
猜你喜欢
  • 2021-01-06
  • 2021-12-01
  • 2021-10-12
  • 2021-02-09
  • 1970-01-01
  • 2019-12-24
  • 2020-05-26
  • 2021-09-29
  • 2023-02-13
相关资源
最近更新 更多