【发布时间】: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 移到条件配方检查上方,我会得到配方未定义,如您所料。
我很想了解为什么我会收到错误“渲染的钩子比上一次渲染时更多”。
【问题讨论】:
-
嗨@juliomalves,感谢您的帮助。部分确实如此,如果没有以下答案,我仍然无法找到解决方法。很高兴现在知道不能有条件地渲染钩子。