Switch语句导致- React限制渲染的数量,以防止无限循环



在我的React代码下面,我得到一个错误:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

如果我注释掉switch语句,错误就会消失。那么,在这个switch语句中是什么导致了这个?这一切都始于尝试使用useState.

const UserBillableGoals = () => {
//Set User
const { user } = useAuth0();
const [goal, setGoal] = useState(0);
const [teamMemberName, setTeamMemberName] = useState("");
switch (user.email) {
case "adam@example.com":
setTeamMemberName("Adam");
setGoal(0);
break;
case "andrew@example.com":
setTeamMemberName("Andrew");
setGoal(12000);
break;
case "kacye@example.com":
setTeamMemberName("Kacye");
setGoal(0);
break;
case "gabriela@example.com":
setTeamMemberName("Gabriela");
setGoal(17000);
break;
case "jazmin@example.com":
setTeamMemberName("Jazmin");
setGoal(14000);
break;
default:
setTeamMemberName("No Name Found");
setGoal(0);
break;
}



return (
<div>

<div>
<p>{year}, {month}</p>
<p>{path}</p>
</div>
</div>
);
}

React是响应式的,对于功能组件来说更是如此。

你的switch语句在组件有机会呈现之前改变了它的状态。每当状态改变时,组件必须重新呈现,从而再次触发switch语句。

您可以通过用useEffect封装交换机来解决这个问题:

useEffect(() => {
switch (user.email) {
case "adam@example.com":
setTeamMemberName("Adam");
setGoal(0);
break;
case "andrew@example.com":
setTeamMemberName("Andrew");
setGoal(12000);
break;
case "kacye@example.com":
setTeamMemberName("Kacye");
setGoal(0);
break;
case "gabriela@example.com":
setTeamMemberName("Gabriela");
setGoal(17000);
break;
case "jazmin@example.com":
setTeamMemberName("Jazmin");
setGoal(14000);
break;
default:
setTeamMemberName("No Name Found");
setGoal(0);
break;
}
}, []);

这确保状态更改只发生在初始呈现

之后。

相关内容

  • 没有找到相关文章