v6版本路由守卫机制深度解析
React Router v6的路由守卫机制相比v5有了重大变化,从传统的组件化守卫转向了更灵活的Hook方式。本文将详细解析v6中的守卫实现方案。
核心变化
v6不再支持<Route>组件的component、render等属性,而是采用element属性配合React元素或组件。这使得路由守卫的实现更加灵活。
基础守卫实现
// 创建一个守卫组件
const ProtectedRoute = () => {
const { isAuthenticated } = useAuth();
const location = useLocation();
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return <Outlet />;
};
// 在路由配置中使用
const router = createBrowserRouter([
{
path: "/",
element: <ProtectedRoute />, // 路由守卫
children: [
{ path: "dashboard", element: <Dashboard /> },
{ path: "profile", element: <Profile /> }
]
}
]);
自定义Hook守卫
const useAuth = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
// 检查认证状态
const token = localStorage.getItem('token');
if (token) {
setIsAuthenticated(true);
}
}, []);
return { isAuthenticated };
};
const AuthGuard = ({ children }) => {
const { isAuthenticated } = useAuth();
if (!isAuthenticated) {
return <Navigate to="/login" />;
}
return children;
};
复现步骤
- 创建基础应用结构
- 使用
useAuth()Hook实现认证逻辑 - 在需要保护的路由上包裹
AuthGuard - 测试未登录用户访问受保护页面的行为
v6的守卫机制更加解耦,但也要求开发者对React Hooks有更深的理解。

讨论