v6路由缓存策略实践
React Router v6相比v5在路由管理上做了重大重构,其中路由缓存策略的处理成为开发者关注的重点。本文将分享在v6中实现路由组件缓存的实用方案。
v6路由缓存问题
在v6中,由于路由切换时组件会重新挂载,导致页面状态丢失。传统的v5中可以通过<Route>的component属性配合keep-alive实现缓存,但在v6中需要采用新的策略。
实现方案
方案一:使用useNavigate + 缓存组件
import { useNavigate, useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
const CacheRoute = ({ children, path }) => {
const navigate = useNavigate();
const location = useLocation();
const [cachedComponents, setCachedComponents] = useState({});
useEffect(() => {
// 缓存当前路由组件
if (location.pathname === path) {
setCachedComponents(prev => ({
...prev,
[path]: children
}));
}
}, [location.pathname]);
return cachedComponents[path] || children;
};
方案二:自定义缓存组件
import { useEffect, useRef } from 'react';
const useCache = () => {
const cacheRef = useRef(new Map());
const get = (key) => cacheRef.current.get(key);
const set = (key, value) => cacheRef.current.set(key, value);
return { get, set };
};
const CachedComponent = ({ component: Component, key }) => {
const cache = useCache();
const cached = cache.get(key);
if (cached) {
return cached;
}
const newComponent = <Component />;
cache.set(key, newComponent);
return newComponent;
};
使用建议
- 对于需要保持状态的页面,如表单、列表页,建议使用缓存策略
- 缓存组件应配合路由参数进行区分,避免数据污染
- 考虑内存占用,对不常用页面设置缓存过期机制
通过以上方案,可以在v6中有效实现路由缓存,提升用户体验。

讨论