如何从路由对象中创建受保护的路由?

时间:2020-10-09 15:24:53

标签: reactjs authentication react-router-dom

我需要您的帮助。我希望用户仅在登录后才能访问仪表板和其他组件。面临的挑战是我有一个路由对象,并且在这种情况下我不知道如何实现受保护的路由。路线如下。我正在使用react-router v6。

Const routes = [
{
Path:"/",
element:<Componen1/>
},
{
Path:"/dashboard",
element:<Componen1/>
},
{
Path:"/list",
element:<Component2/>
}
...

]

1 个答案:

答案 0 :(得分:0)

简单的方法是,如果用户未登录,则在react-router-dom v6中使用<Navigate />重定向到登录

const routes = [
        { 
          path: 'dashboard', 
          element: (
             <ProtectedRoute>
                 <DashboardView />
             </ProtectedRoute>
          ) 
       },
       {
          Path:"/list",
          element:(
             <ProtectedRoute>
                <ListComponent2/>
             </ProtectedRoute>
          ) 
       },
       {
          Path:"/login",
          element:(
             <PublicRoute>
                <LoginComponent/>
             </PublicRoute>
          ) 
       },
       ...other paths
    ]  

ProtectedRoute.js

import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "src/hooks/useAuth";

export function ProtectedRoute({ children }) {
    const { isAuth } = useAuth();
    const location = useLocation();

    return isAuth ? (
        children
    ) : (
            <Navigate
                to="/login"
                state={{ from: location }}
            />
        );
}

PublicRoute.js

import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "src/hooks/useAuth";

export function PublicRoute({ children }) {
    let { isAuth } = useAuth();
    let location = useLocation();

    return isAuth ? (
        <Navigate
            to="/dashboard"
            state={{ from: location }}
        />
    ) : (
            children
        );
}