导航组件 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组件用于包装用户不需要验证的页面,例如SignInSignUpForgotPassword , 和 ResetPassword 页。

  3. PrivateRoute组件用于包装私人页面(需要验证),例如主页。 PrivateRoute里面有一些布局。其中之一称为 Dashboard 布局,用于包装 Drawer (Sidebar/Navigation) 组件和 Home 页面。

  4. 如果用户未通过 SignIn 页面登录,应用程序将 return SignIn 页面。 如果用户已登录,应用程序将 return Home 页面。

当前情况如下:

注意:复选符号(✅)代表我想要的条件,叉号(❌)代表错误或不需要的条件。

  1. 满足以上所有规格。 ✅

  2. 用户第一次运行应用程序时,SignIn页面是returned,因为用户尚未登录。✅

  3. 如果用户没有通过SignIn页面登录并在地址栏输入“/”路由(访问Home页面),应用将不要将用户重定向到 Home 页面而不是 returning SignIn 页面。 ✅

  4. 如果用户通过 SignIn 页面成功登录,应用程序将 return Home 页面(使用“/”路由)。 ✅

  5. 如果用户通过Home页面登录并在地址栏输入“/sign-in”路由(访问SignIn页面),应用 return 错误:❌

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 页面(“/”路径),而不是 return 错误。

这是 AuthenticationRoute 的代码:

function AuthenticationRoute(props) {
  const { children } = props;

  const userProfile = readUserProfileFromLocalStorage();

  return userProfile ? <Navigate replace to="/sign-in" /> : children;
}

这里是 PrivateRoute:

的代码
function PrivateRoute(props) {
  const { children } = props;

  const userProfile = readUserProfileFromLocalStorage();

  return userProfile ? (
    <Dashboard>{children}</Dashboard>
  ) : (
    <Navigate replace to="/sign-in" />
  );
}

这里是游乐场:https://codesandbox.io/s/Whosebug-auth-private-routes-5xxrw

我使用 react-router-dom v5 做了类似的事情,但没有 return 错误。一切都很好。

那么,这个案例的解决方案是什么?

您的 AuthenticationRoute 组件存在问题。当定义 userProfile 时,您将用户重定向到 /sign-in,这会导致无限循环,因为它是同一页面。它应该导航到 /

function AuthenticationRoute(props) {
  const { children } = props;

  const userProfile = readUserProfileFromLocalStorage();

  return userProfile ? <Navigate replace to="/" /> : children;
}