React Router v6路由守卫实现与权限控制最佳实践
随着React Router v6的发布,路由系统进行了重大重构,其中最显著的变化是移除了<Route>组件的component和render属性,转而使用element属性。这为实现更灵活的路由守卫提供了新的可能性。
核心变化
在v6中,路由配置方式从:
<Route path="/admin" component={Admin} />
变为:
<Route path="/admin" element={<Admin />} />
路由守卫实现方案
1. 基础权限守卫组件
const ProtectedRoute = ({ allowedRoles, children }) => {
const { user } = useAuth();
if (!user) {
return <Navigate to="/login" replace />;
}
if (allowedRoles && !allowedRoles.includes(user.role)) {
return <Navigate to="/unauthorized" replace />;
}
return children;
};
2. 路由配置示例
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route
path="/admin"
element={
<ProtectedRoute allowedRoles={['admin']}>
<Admin />
</ProtectedRoute>
}
/>
</Route>
</Routes>
3. 高级守卫模式
const AuthGuard = ({ children }) => {
const location = useLocation();
// 检查用户认证状态
if (!isAuthenticated()) {
return (
<Navigate
to="/login"
state={{ from: location }}
replace
/>
);
}
return children;
};
迁移注意事项
- 所有路由组件都需要通过
element属性传入 useRouteMatch已被废弃,使用useMatches替代Switch组件被Routes替代- 保持原有权限逻辑不变,只需调整组件结构
最佳实践
- 将守卫逻辑封装为可复用组件
- 合理设计路由层级结构
- 注意权限验证的性能开销
- 做好错误边界处理

讨论