带有反应路由器 v6 的受保护路由 [英] Protected route with react router v6
本文介绍了带有反应路由器 v6 的受保护路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 react-router 的新版本 6 编写 ProtectedRoute 的正确方法是什么?我写了这个,但不是路线
What is correct way to write a ProtectedRoute with new version 6 of react-router? I wrote this one, but it's not a route
const PrivateRoute = ({ component: Component, ...props }) => {
if (!Component) return null;
return props.isAuthenticated
? <Component />
: <Navigate to={props.redirectLink} /> }
export default PrivateRoute;
推荐答案
这是我使用 useRoutes 实现私有路由的工作示例.
Here is my working example for implementing private routes by using 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',
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 /> },
],
},
],
},
{
path: '/',
element: !isLoggedIn ? <MainLayout /> : <Navigate to="/app/dashboard" />,
children: [
{ path: 'login', element: <Login /> },
{ path: '/', element: <Navigate to="/login" /> },
],
},
];
export default routes;
这篇关于带有反应路由器 v6 的受保护路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文