react实现beforeEach
React 实现类似路由守卫的 beforeEach 功能
在 React 中实现类似 Vue 路由守卫的 beforeEach 功能,可以通过 React Router 提供的导航守卫机制结合自定义逻辑完成。
使用 React Router v6 的导航守卫
React Router v6 提供了 useNavigate 和 useLocation 钩子,结合 useEffect 可以实现路由跳转前的拦截逻辑。

import { useNavigate, useLocation } from 'react-router-dom';
import { useEffect } from 'react';
function RouterGuard({ children }) {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
// 在这里添加路由跳转前的逻辑
const isAuthenticated = checkAuth(); // 自定义认证检查
if (!isAuthenticated && location.pathname !== '/login') {
navigate('/login', { replace: true });
}
}, [location, navigate]);
return children;
}
自定义高阶组件封装
可以创建一个高阶组件来封装路由守卫逻辑,使代码更易于复用。

function withRouterGuard(WrappedComponent, guardFn) {
return function(props) {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
guardFn({ navigate, location });
}, [location, navigate]);
return <WrappedComponent {...props} />;
};
}
在路由配置中应用守卫
可以在路由配置中为需要保护的路由添加守卫组件。
const routes = [
{
path: '/',
element: (
<RouterGuard>
<HomePage />
</RouterGuard>
),
},
{
path: '/dashboard',
element: (
<RouterGuard>
<Dashboard />
</RouterGuard>
),
},
];
实现完整的认证流程示例
function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/protected"
element={
<RequireAuth>
<ProtectedPage />
</RequireAuth>
}
/>
</Routes>
);
}
function RequireAuth({ children }) {
const auth = useAuth();
const location = useLocation();
if (!auth.user) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}
处理异步验证逻辑
对于需要异步验证的场景,可以使用 Promise 或 async/await。
useEffect(() => {
const checkAccess = async () => {
const hasAccess = await verifyUserAccess();
if (!hasAccess) {
navigate('/no-access');
}
};
checkAccess();
}, [location, navigate]);
这些方法提供了在 React 中实现路由跳转前逻辑的各种方式,可以根据具体需求选择最适合的实现方案。






