React Router v6的路由缓存机制是开发者关注的重点之一。相比v5版本,v6采用了更灵活的缓存策略。在v6中,通过useNavigate和useLocation钩子配合useEffect实现页面缓存功能。
首先,在路由配置中启用缓存:
const routes = [
{
path: '/home',
element: <Home />,
// v6支持通过自定义属性标记需要缓存的组件
shouldCache: true
}
]
其次,创建缓存管理Hook:
import { useEffect, useRef } from 'react';
export const usePageCache = (key) => {
const cacheRef = useRef({});
useEffect(() => {
// 页面卸载时保存状态
return () => {
if (cacheRef.current[key]) {
localStorage.setItem(`cache_${key}`, JSON.stringify(cacheRef.current[key]));
}
};
}, [key]);
return cacheRef.current;
};
最后,在组件中使用:
function Home() {
const cache = usePageCache('home');
const location = useLocation();
useEffect(() => {
// 恢复缓存状态
const saved = localStorage.getItem('cache_home');
if (saved) {
Object.assign(cache, JSON.parse(saved));
}
}, [location]);
return <div>Home Content</div>;
}
这种实现方式确保了用户在不同路由间切换时,关键页面状态得以保留。

讨论