[英]Maximum update depth exceeded from Navigate component react-router-dom v6
我正在使用react-router-dom v6
來控制我的 React Js 應用程序的路由。
以下是規格:
我正在創建AuthenticationRoute
和PrivateRoute
組件。
AuthenticationRoute
組件用於包裝用戶不需要進行身份驗證的頁面,例如SignIn
、 SignUp
、 ForgotPassword
和ResetPassword
頁面。
PrivateRoute
組件用於包裝私有頁面(需要身份驗證),例如主頁。 在PrivateRoute
內部,有一些布局。 其中之一稱為Dashboard
布局,用於包裝Drawer
(側邊欄/導航)組件和Home
。
如果用戶沒有通過SignIn
頁面登錄,應用程序將返回SignIn
頁面。 如果用戶已登錄,應用程序將返回Home
。
以下是目前的情況:
注意:勾號 (✅) 代表我想要的條件,而叉號 (❌) 代表錯誤或不需要的條件。
滿足上述所有規格。 ✅
用戶第一次運行應用,由於用戶沒有登錄,返回登錄頁面SignIn
如果用戶沒有登錄並通過SignIn
頁面輸入“/”路由到地址欄(訪問Home
),應用程序不會將用戶重定向到Home
,而是返回SignIn
頁面。 ✅
如果用戶通過SignIn
頁面成功登錄,應用程序將返回Home
(帶有“/”路由)。 ✅
如果用戶已經登錄並通過Home
輸入“/sign-in”路由到地址欄(訪問登錄頁面),應用程序返回錯誤: SignIn
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
at Navigate (https://5xxrw.csb.app/node_modules/react-router/index.js:247:12)
at AuthenticationRoute (https://5xxrw.csb.app/src/components/Routes/AuthenticationRoute.jsx:21:26)
at Routes (https://5xxrw.csb.app/node_modules/react-router/index.js:306:18)
at App
at Router (https://5xxrw.csb.app/node_modules/react-router/index.js:266:18)
at BrowserRouter (https://5xxrw.csb.app/node_modules/react-router-dom/index.js:284:18)
應用程序應將用戶導航回Home
(“/”路由),而不是返回錯誤。
這里是操場: https://codesandbox.io/s/stackoverflow-auth-private-routes-5xxrw
我使用react-router-dom v5
做了類似的事情,但沒有返回錯誤。 一切都很好。
那么,這種情況的解決方案是什么?
您的AuthenticationRoute
組件存在問題。 在定義userProfile
時,您將用戶重定向到/sign-in
,這會導致無限循環,因為它是同一頁面。 它應該導航到/
function AuthenticationRoute(props) {
const { children } = props;
const userProfile = readUserProfileFromLocalStorage();
return userProfile ? <Navigate replace to="/" /> : children;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.