React Router v6 路由缓存清理机制
在 React Router v6 中,路由缓存机制发生了重要变化。相比 v5 的 Switch 组件自动清理缓存,v6 采用了更灵活的 useNavigate 和 useLocation API 来控制页面状态。
缓存清理方案
1. 使用 useNavigate 进行路由跳转时清理缓存
const navigate = useNavigate();
const handleNavigate = (path) => {
// 清理当前路由状态
navigate(path, { replace: true });
};
2. 自定义缓存清理 Hook
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const useCacheClear = (clearCondition) => {
const location = useLocation();
useEffect(() => {
if (clearCondition) {
// 清理缓存逻辑
window.sessionStorage.clear();
}
}, [location, clearCondition]);
};
3. 路由守卫中的缓存清理
const PrivateRoute = ({ children }) => {
const location = useLocation();
useEffect(() => {
// 页面切换时清理特定缓存
if (location.pathname) {
const cacheKey = `cache_${location.pathname}`;
sessionStorage.removeItem(cacheKey);
}
}, [location]);
return children;
};
可复现步骤
- 在 v6 项目中创建多个路由组件
- 使用
useNavigate进行页面跳转 - 观察缓存清理行为
- 验证自定义缓存清除逻辑是否生效
通过以上方案,可以有效管理 React Router v6 中的路由缓存问题,确保应用性能和用户体验。

讨论