簡體   English   中英

導航組件 react-router-dom v6 超出了最大更新深度

[英]Maximum update depth exceeded from Navigate component react-router-dom v6

我正在使用react-router-dom v6來控制我的 React Js 應用程序的路由。

以下是規格:

  1. 我正在創建AuthenticationRoutePrivateRoute組件。

  2. AuthenticationRoute組件用於包裝用戶不需要進行身份驗證的頁面,例如SignInSignUpForgotPasswordResetPassword頁面。

  3. PrivateRoute組件用於包裝私有頁面(需要身份驗證),例如主頁。 PrivateRoute內部,有一些布局。 其中之一稱為Dashboard布局,用於包裝Drawer (側邊欄/導航)組件和Home

  4. 如果用戶沒有通過SignIn頁面登錄,應用程序將返回SignIn頁面。 如果用戶已登錄,應用程序將返回Home

以下是目前的情況:

注意:勾號 (✅) 代表我想要的條件,而叉號 (❌) 代表錯誤或不需要的條件。

  1. 滿足上述所有規格。

  2. 用戶第一次運行應用,由於用戶沒有登錄,返回登錄頁面SignIn

  3. 如果用戶沒有登錄並通過SignIn頁面輸入“/”路由到地址欄(訪問Home ),應用程序不會將用戶重定向到Home ,而是返回SignIn頁面。

  4. 如果用戶通過SignIn頁面成功登錄,應用程序將返回Home (帶有“/”路由)。

  5. 如果用戶已經登錄並通過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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM