代码之家  ›  专栏  ›  技术社区  ›  adherb

如何修复错误:使用带有useEffect的SWR时,渲染的钩子比上一次渲染时多

  •  1
  • adherb  · 技术社区  · 3 年前

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

    我的代码如下:

    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钩子,它工作得非常完美,正如我在注释useffect时所预期的那样。如果我将useffect移到条件配方检查之上,我得到的配方将如您所期望的那样未定义。

    我很想理解为什么会出现“渲染的钩子比上次渲染时多”的错误。

    1 回复  |  直到 3 年前
        1
  •  0
  •   Nir Berko    3 年前

    不要在循环、条件或嵌套函数中调用钩子。相反,总是在React函数的顶层使用钩子。您可以在文档中阅读更多内容 here

    在您的情况下,您可以执行以下操作:

    const { id } = router.query;
    const { data: post } = usePost(id);
    
    useEffect(() => {
      if (recipe && typeof post.title === "string") {
        setTitle(post.title);
      }
    }, [recipe]);
    
    if (!recipe) {
      return <div>Loading...</div>;
    }
    
    return ....;
    
    推荐文章