已创建具有以下版本的react js仪表板应用程序 “ react-router”:“ ^ 6.0.0-beta.0”, “ react-router-dom”:“ ^ 6.0.0-beta.0”
必须为该应用实现受保护的路由实例,从上述反应路由器v6开始,受保护的路由与我以前在v5上使用的路由有所不同。有人可以告诉我如何为此添加受保护的路由吗?谢谢您的时间!
这是app.js
import 'react-perfect-scrollbar/dist/css/styles.css';
import React from 'react';
import { useRoutes } from 'react-router-dom';
import { ThemeProvider } from '@material-ui/core';
import GlobalStyles from 'src/components/GlobalStyles';
import 'src/mixins/chartjs';
import theme from 'src/theme';
import routes from 'src/routes';
const App = () => {
const routing = useRoutes(routes);
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
{routing}
</ThemeProvider>
);
};
export default App;
这是route.js代码
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <AccountView /> },
{ path: 'reporting', element: <CustomerListView /> },
{ path: 'dashboard', element: <DashboardView /> },
{ path: 'classrooms', element: <ProductListView /> },
{ path: 'settings', element: <SettingsView /> },
{ path: '*', element: <Navigate to="/404" /> }
]
},
{
path: '/',
element: <MainLayout />,
children: [
{ path: 'login', element: <LoginView /> },
{ path: 'register', element: <RegisterView /> },
{
path: 'RegisterViewContactDetails',
element: <RegisterViewContactDetails />
},
{ path: 'ForgotPassword', element: <ForgotPassword /> },
{ path: 'RestPassword', element: <RestPassword /> },
{ path: '404', element: <NotFoundView /> },
{ path: '/', element: <Navigate to="/login" /> },
{ path: '*', element: <Navigate to="/404" /> }
]
}
];
export default routes;
答案 0 :(得分:1)
这是我的工作示例,该示例通过使用 useRoutes 钩子实现受保护的路由。
App.js
import routes from './routes';
import { useRoutes } from 'react-router-dom';
function App() {
const { isLoggedIn } = useSelector((state) => state.auth);
const routing = useRoutes(routes(isLoggedIn));
return (
<>
{routing}
</>
);
}
routes.js
import { Navigate,Outlet } from 'react-router-dom';
const routes = (isLoggedIn) => [
{
path: '/app', // protected routes
element: isLoggedIn ? <DashboardLayout /> : <Navigate to="/login" />,
children: [
{ path: '/dashboard', element: <Dashboard /> },
{ path: '/account', element: <Account /> },
{ path: '/', element: <Navigate to="/app/dashboard" /> },
{
path: 'member',
element: <Outlet />,
children: [
{ path: '/', element: <MemberGrid /> },
{ path: '/add', element: <AddMember /> },
],
},
],
},
{ // public routes
path: '/',
element: !isLoggedIn ? <MainLayout /> : <Navigate to="/app/dashboard" />,
children: [
{ path: 'login', element: <Login /> },
{ path: '/', element: <Navigate to="/login" /> },
],
},
];
export default routes;