[英]Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop - ProtectedRoutes Component
I am attempting to create a ProtectedRoutes component, however, I seem to have created an infinite loop somewhere that I can't seem to figure out.我正在尝试创建一个 ProtectedRoutes 组件,但是,我似乎在某个我似乎无法弄清楚的地方创建了一个无限循环。 I'm a beginner.
我是初学者。
It should check if there is a cookie stored, and if so, go to the component.它应该检查是否存储了 cookie,如果有,则转到组件。 If not, it should navigate back to the main page.
如果没有,它应该导航回主页。
ProtectedRoutes.js ProtectedRoutes.js
import React, { Component, useState } from "react";
import { Route, Navigate } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();
export default function ProtectedRoutes({component: Component, ...rest}) {
const [auth, setAuth] = useState(false);
//get cookie from browser if logged in
const token = cookies.get("TOKEN");
if (token) {
setAuth(true);
};
return auth ? <Component /> : <Navigate to="/" />
}
Yow problem Is heaw.你的问题是heaw。
export default function ProtectedRoutes({component: Component, ...rest}) {
const [auth, setAuth] = useState(false);
//get cookie from browser if logged in
const token = cookies.get("TOKEN");
if (token) {
setAuth(true);
};
return auth ? <Component /> : <Navigate to="/" />
}
In ProtectedRoutes<\/code> component, you're setting a state (
setAuth<\/code> in this case) directly inside the component, this is what happens when you do that:
在
ProtectedRoutes<\/code>组件中,您直接在组件内部设置状态(在本例中为
setAuth<\/code> ),当您这样做时会发生以下情况:
React re-renders a component every time a state change is detected thus when you wrote每次检测到状态更改时,React 都会重新渲染组件,因此当您编写时
export default function ProtectedRoutes({component: Component, ...rest}) {
...
if (token) {
setAuth(true);
};
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.