react router实现路由拦截
路由拦截的实现方式
在React Router中实现路由拦截通常涉及以下方法,核心思路是通过高阶组件或自定义路由组件对导航行为进行控制。
使用高阶组件封装路由
通过高阶组件包裹目标路由,在渲染前进行权限或条件校验:
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
// 使用示例
<PrivateRoute
path="/dashboard"
component={Dashboard}
isAuthenticated={userLoggedIn}
/>
自定义路由组件
创建继承自Route的自定义组件,重写渲染逻辑:
class AuthRoute extends Route {
render() {
const { fallbackPath, authCheck, ...props } = this.props;
return authCheck()
? super.render()
: <Redirect to={fallbackPath} />;
}
}
// 使用示例
<AuthRoute
path="/admin"
component={AdminPanel}
authCheck={() => checkAdminRole()}
fallbackPath="/no-access"
/>
路由守卫模式
在全局路由配置中使用onEnter钩子(v5及之前版本):
<Route
path="/profile"
component={Profile}
onEnter={(nextState, replace) => {
if (!hasToken()) replace('/auth');
}}
/>
使用useNavigate拦截
React Router v6+推荐方案,通过自定义导航钩子:
const useAuthRedirect = () => {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
const publicPaths = ['/login', '/register'];
if (!publicPaths.includes(location.pathname) && !isAuth()) {
navigate('/login', { state: { from: location } });
}
}, [location]);
};
// 在根组件调用
function App() {
useAuthRedirect();
return <Routes>...</Routes>;
}
动态路由加载拦截
结合React.lazy实现异步路由拦截:
const LazyAdmin = React.lazy(() => {
return verifyAdmin().then(
() => import('./Admin'),
() => ({ default: () => <Redirect to="/" /> })
);
});
<Route path="/admin" element={
<Suspense fallback={<Spinner />}>
<LazyAdmin />
</Suspense>
} />
路由配置集中管理
通过声明式配置实现集中式路由守卫:
const routeConfig = [
{
path: '/',
element: <Home />,
guards: [checkGuest],
},
{
path: '/settings',
element: <Settings />,
guards: [checkAuth, checkSubscription],
redirect: '/upgrade',
}
];
const GuardedRoutes = () => {
return (
<Routes>
{routeConfig.map((route) => (
<Route
key={route.path}
path={route.path}
element={<RouteGuard {...route} />}
/>
))}
</Routes>
);
};
每种方案适用于不同场景,v6+推荐使用组合式导航钩子方案,v4/v5可采用高阶组件模式。实际选择应考虑项目架构版本和技术栈的统一性。







