在一个应用程序中,我有两种类型的用户
vendor
和buyer
想要管理路由,这样供应商就无法访问买家页面,反之亦然,使用React Router Dom V6。尝试这样做应该会路由到访问被拒绝的页面。
登录页面的登录逻辑
if (res.data.data.user?.role?.name.toLowerCase() === "vendor") {
navigate("/dashboard")
}
else {
navigate("/buyer-dashboard")
}
App.jsx
<BrowserRouter>
<BuyerRoute />
<VendorRoute />
<PublicRoute />
</BrowserRouter>
公共路由.jsx
<Routes>
<Route index element={<Login />} />
<Route path='/signup' element={<SignUp />} />
<Route path='/email-confirmation' element={<Confirmation />} />
<Route path='/forget-password' element={<ForgetPassword />} />
<Route path='/set-password/:email' element={<SetPassword />} />
<Route path='*' element={<>404</>} />
</Routes>
BuyerRoute.jsx
<Routes>
<Route path="/buyer-dashboard" element={<Dashboard />} />
<Route path="/other" element={< Other />} />
</Routes>
VendorRoute.jsx
<Routes>
<Route path="/dashboard" element={<VendorDashboard />} />
<Route path="/items" element={< Items />} />
</Routes>
登录成功路由到预期页面,购买我更改地址栏中的路线,当我以
dashboard
身份登录时,我可以导航到 buyer
。
对于您在应用程序中想要的方法,您需要使用受保护的路由,您可以在此博客中了解更多信息: [:https://blog.logrocket.com/authentication-react-router-v6/
创建正常路线
import { createBrowserRouter } from 'react-router-dom';
//import all the page components here
export const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
{
index: true,
element: <Login />,
},
{
path: 'signup',
element: <SignUp />,
},
{
path: 'dashboard',
element: (
<ProtectedRoute allowedRoles={roles.vendor}>
<VendorDashboard />
</ProtectedRoute>
),
},
{
path: 'items',
element:(
<ProtectedRoute allowedRoles={roles.vendor}>
<Items />
</ProtectedRoute>
),
},
{
path: 'buyer-dashboard',
element:(
<ProtectedRoute allowedRoles={roles.buyer}>
<Dashboard />
</ProtectedRoute>
),
},
{
path: 'other',
element:(
<ProtectedRoute allowedRoles={roles.buyer}>
<Other />
</ProtectedRoute>
),
},
],},]);
const roles = {
buyer: ['buyer-dashboard', 'other'],
vendor: ['dashboard', 'items'],
};
创建一个函数来检索登录时用户的角色
const getUserRole = () => {
return 'superAdmin';
};
现在为受保护的路线制作一个组件
import { Navigate } from 'react-router-dom';
const ProtectedRoute = ({ children, allowedRoles }) => {
const userRole = getUserRole();
const isAuthenticated = true;
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
if (!allowedRoles.includes(userRole)) {
return <Navigate to="/unauthorized" replace />;
}
return children // <Outlet />; tyou can use Outlet here to
};
export default ProtectedRoute;