react实现路由守卫
React 路由守卫实现方法
在 React 中实现路由守卫(Route Guard)可以通过多种方式完成,以下是常见的几种方法:
使用高阶组件(HOC)包装路由
创建高阶组件来检查用户权限或登录状态,再决定是否渲染目标组件:

const withAuth = (Component) => {
return (props) => {
const isAuthenticated = checkAuth(); // 自定义认证逻辑
return isAuthenticated ? (
<Component {...props} />
) : (
<Navigate to="/login" replace />
);
};
};
// 使用方式
<Route path="/protected" element={withAuth(ProtectedComponent)} />
利用 React Router v6 的 element 属性
在路由配置中直接进行守卫逻辑判断:
<Route
path="/dashboard"
element={
<RequireAuth>
<Dashboard />
</RequireAuth>
}
/>
// RequireAuth 组件实现
function RequireAuth({ children }) {
const auth = useAuth();
if (!auth.user) {
return <Navigate to="/login" />;
}
return children;
}
自定义路由组件
创建自定义路由组件封装守卫逻辑:

const PrivateRoute = ({ component: Component, ...rest }) => {
const { isAuthenticated } = useAuth();
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/login" }} />
)
}
/>
);
};
// 使用方式
<PrivateRoute path="/admin" component={AdminPanel} />
使用路由拦截器
在全局路由变化时进行拦截:
function App() {
const location = useLocation();
const navigate = useNavigate();
useEffect(() => {
if (!isAuthPage(location.pathname) && !isAuthenticated()) {
navigate('/login', { state: { from: location } });
}
}, [location]);
return <Routes>...</Routes>;
}
角色权限控制
对于需要基于角色的权限控制:
const RoleRoute = ({ roles, children }) => {
const userRole = getUserRole(); // 获取用户角色
return roles.includes(userRole) ? children : <Navigate to="/unauthorized" />;
};
// 使用方式
<Route
path="/admin"
element={
<RoleRoute roles={['admin']}>
<AdminPage />
</RoleRoute>
}
/>
注意事项
- 守卫逻辑应该与路由配置解耦,便于维护
- 考虑添加加载状态处理异步验证
- 登录后重定向到原始请求页面
- 对于嵌套路由,守卫逻辑需要应用到每个需要保护的层级
以上方法可以根据具体项目需求组合使用,React Router v6 推荐使用 element 属性配合自定义组件的方式实现路由守卫。






