use*_*131 2 reactjs react-router react-router-dom
使用以下版本创建了一个 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;
Run Code Online (Sandbox Code Playgroud)
这是 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;
Run Code Online (Sandbox Code Playgroud)
这是我使用useRoutes钩子实现受保护路由的工作示例。
应用程序.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}
</>
);
}
Run Code Online (Sandbox Code Playgroud)
路由.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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
898 次 |
| 最近记录: |