react-router routerprovider 中未受保护和受保护的路由

问题描述 投票:0回答:1

我之前用这种方式使用旧的反应路由器方式构建了一个应用程序

App.jsx

if(auth){
    return <AppProtectedRoutes/>
}

return <AppUnprotectedRoutes/>

应用程序保护的路线

<Routes>
    <Route path='/' element/>
    <Route path='/dashboard' element/>
<Routes>

应用程序未受保护的路由

<Routes>
    <Route path='/login' element/>
    <Route path='/signup' element />
    <Route path='/onboard' element />
<Routes>

如何将它们转换为 RouteObject,以便经过身份验证的用户只能访问“受保护”,未经身份验证的用户只能访问“不受保护”?

另外,由于 RouteProvider 将位于 index.js 文件中,那么 App.js 除了主要逻辑之外还应该包含什么?

reactjs react-router react-router-dom
1个回答
0
投票

首先假设您正在使用身份验证上下文来维护用户会话,您可以在其中检查用户是否登录。

创建一个名为 ProtectedRoutes 的新组件。该组件将检查用户是否登录。如果未登录,它将重定向到登录页面,否则它将呈现受保护的路由。

ProtectedRoutes.jsx

import React from "react";
import { Outlet, Navigate } from "react-router-dom";
import { useAuth } from "../Context/AuthContext";

const ProtectedRoutes = () => {
  const { user } = useAuth();
  return user ? <Outlet /> : <Navigate to="/login" />;
};

export default ProtectedRoutes;

它正在检查AuthContext中的用户是否存在并相应地处理重定向。 (您可能有不同的逻辑来检查会话,因此您也可以使用它。)

在 App.jsx 中,您设置了路线;您可以这样设置受保护的路由:

应用程序.jsx

<Routes>
  {/* Unprotected Routes Here  */}
    <Route path='/login' element/>
    <Route path='/signup' element />
    <Route path='/onboard' element />

  {/* Protected Routes Here  */}
  <Route element={<ProtectedRoutes />}>
    <Route path='/' element/>
    <Route path='/dashboard' element/>
  </Route>
<Routes>

发生的情况是,您像往常一样定义了路由,但所有受保护的路由都包装在您的 ProtectedRoute 组件中。

您的浏览器路由逻辑应该位于您的 App.jsx 而不是 index.js 文件中。

© www.soinside.com 2019 - 2024. All rights reserved.