React Query/RTK Query路由级缓存:如何获取路由唯一缓存键?
React Query & RTK Query 路由级缓存的标识方案
针对你提到的路由级单次请求场景(同一路由复用缓存、切换路由返回后重新获取),React Router本身就提供了可直接用于设置缓存键的路由唯一标识,核心就是当前路由的路径信息,具体实现分两种库来说:
React Query 实现方式
你可以直接将当前路由的location.pathname(比如/X)作为缓存键的一部分,配合React Query的缓存控制逻辑实现需求:
- 定义查询时,把路径加入缓存键数组:
const { data } = useQuery( ['route-data', location.pathname], // 用路径作为缓存键的一部分 () => fetchRouteData(location.pathname), { staleTime: 0, // 标记数据立即过期,确保返回路由时重新获取 cacheTime: 0 // 可选:离开路由后立即清除缓存,节省内存 } ); - 同一路由下的所有组件使用相同的缓存键,自然会复用同一份缓存数据;当切换到
/Y再返回/X时,因为缓存键对应的标记数据已过期,React Query会自动重新发起请求。 - 额外优化:可以在路由组件的
useEffect中监听路由卸载事件,主动清除该路由的缓存:useEffect(() => { return () => { queryClient.removeQueries(['route-data', location.pathname]); }; }, [queryClient, location.pathname]);
RTK Query 实现方式
RTK Query的缓存键由API endpoint和传入的查询参数共同生成,你可以把路由路径作为查询参数传入,配合配置项实现需求:
- 定义API endpoint时接收路径参数:
const api = createApi({ reducerPath: 'routeApi', baseQuery: fetchBaseQuery({ baseUrl: '/' }), endpoints: (builder) => ({ getRouteData: builder.query({ query: (path) => `data${path}` }) }) }); - 在路由组件中使用时,传入当前路径作为参数,并配置
refetchOnMountOrArgChange: true:const { data, refetch } = useGetRouteDataQuery(location.pathname, { refetchOnMountOrArgChange: true // 路由挂载时重新获取数据 }); - 同一路由下的组件调用该查询时,因为参数相同,会复用缓存;切换路由返回后,路由组件重新挂载,RTK Query会根据配置重新发起请求。
- 也可以在路由卸载时重置该endpoint的缓存:
useEffect(() => { return () => { dispatch(api.util.resetApiState()); }; }, [dispatch, api]);
总结
路由加载时,React Router提供的location.pathname、match.path(针对动态路由)都是天然的唯一标识,直接用来构建缓存键即可满足你的需求。不需要额外生成自定义标识,利用路由自身的路径信息就能精准控制缓存的复用与失效。
内容的提问来源于stack exchange,提问作者Probosckie
相关产品推荐
相关产品推荐

