react如何拦截路由
拦截路由的实现方法
在React中拦截路由通常用于权限控制、数据预加载或页面跳转前的确认操作。以下是几种常见的实现方式:
使用React Router的导航守卫
React Router v6提供了useNavigate和useBeforeUnload等钩子来实现路由拦截:
import { useNavigate, useLocation } from 'react-router-dom';
function PrivateRoute({ children }) {
const navigate = useNavigate();
const location = useLocation();
const isAuthenticated = checkAuth(); // 自定义认证检查
if (!isAuthenticated) {
navigate('/login', { state: { from: location } });
return null;
}
return children;
}
自定义路由组件包装器
创建高阶组件包裹需要保护的路由:
function AuthWrapper({ children }) {
const [allowed, setAllowed] = useState(false);
useEffect(() => {
async function checkPermission() {
const hasAccess = await verifyPermissions();
setAllowed(hasAccess);
}
checkPermission();
}, []);
return allowed ? children : <div>Loading or Access Denied</div>;
}
使用路由配置拦截
在路由配置中直接加入拦截逻辑:
const router = createBrowserRouter([
{
path: '/dashboard',
element: <AuthCheck><Dashboard /></AuthCheck>,
loader: async () => {
const data = await fetchData();
if (!data) throw new Response('', { status: 401 });
return data;
}
}
]);
页面跳转前确认
实现离开页面前的确认对话框:
import { unstable_useBlocker as useBlocker } from 'react-router-dom';
function ConfirmNavigation() {
const blocker = useBlocker(
({ currentLocation, nextLocation }) =>
currentLocation.pathname !== nextLocation.pathname
);
useEffect(() => {
if (blocker.state === 'blocked') {
const confirm = window.confirm('Are you sure you want to leave?');
if (confirm) blocker.proceed();
else blocker.reset();
}
}, [blocker]);
}
路由加载拦截
利用React Router的loader函数在路由加载前拦截:
export async function loader({ params }) {
const resource = await getResource(params.id);
if (!resource) {
throw new Response('Not Found', { status: 404 });
}
return resource;
}
每种方法适用于不同场景,需要根据具体需求选择实现方式。权限验证通常使用高阶组件或路由包装器,数据预加载适合用loader拦截,关键操作确认适合使用导航守卫。







