我在使用带有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移到条件配方检查之上,我得到的配方将如您所期望的那样未定义。
我很想理解为什么会出现“渲染的钩子比上次渲染时多”的错误。
不要在循环、条件或嵌套函数中调用钩子。相反,总是在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 ....;