如何在RTK Query的一个端点中读取另一个端点的缓存数据?
解决RTK Query跨端点访问缓存并过滤炸弹状态的问题
如何访问另一个端点的缓存值
在RTK Query中,你可以通过以下方式在Bomb端点的更新逻辑里获取Time端点(getTime)的缓存数据:
- 利用
api.getState()和端点的select方法
在getBombs的更新逻辑(比如WebSocket订阅的updateQueryData)中,你可以调用api.getState()获取整个Redux状态,再通过api.endpoints.getTime.select()这个selector函数提取getTime的缓存数据。
示例代码:
api.injectEndpoints({ endpoints: (build) => ({ getBombs: build.subscription({ query: () => ({ /* WebSocket 配置 */ }), updateQueryData: (draft, { data: newBombs }) => { // 获取getTime端点的缓存数据 const timeSelector = api.endpoints.getTime.select(); const timeCache = timeSelector(api.getState()); const currentGameTime = timeCache?.data; if (currentGameTime) { // 过滤掉缓存中已爆炸的炸弹 const activeBombs = draft.filter(bomb => bomb.explodeTime > currentGameTime); // 合并新炸弹并再次过滤(防止新炸弹已经过期) const updatedBombs = [...activeBombs, ...newBombs].filter(bomb => bomb.explodeTime > currentGameTime); // 更新draft draft.length = 0; draft.push(...updatedBombs); } else { // 如果getTime还未加载完成,暂时添加新炸弹 draft.push(...newBombs); } }, }), }), });
- 组件层面的补充方案(如果需要)
如果需要在组件中基于当前时间过滤炸弹,也可以同时使用两个Query Hook,通过select参数过滤数据:
const { data: currentGameTime } = useGetTimeQuery(); const { data: bombs } = useGetBombsQuery(undefined, { select: (data) => { if (!currentGameTime) return data; return data.filter(bomb => bomb.explodeTime > currentGameTime); }, });
这样操作是否安全?
是安全的,但需要注意两个关键点:
- 处理缓存未加载的情况:要判断
getTime的缓存是否存在(比如timeCache?.data),避免初始阶段currentGameTime为undefined导致逻辑出错。 - RTK Query的状态一致性:RTK Query的缓存是基于Redux状态的immutable数据,在
updateQueryData这类Redux reducer流程中访问,不会出现并发修改的问题,因为所有更新都是串行处理的。
另外,RTK Query的select方法是官方提供的标准方式,用于安全提取端点缓存数据,不会破坏RTK Query的缓存管理机制。
内容的提问来源于stack exchange,提问作者Marci
相关产品推荐
相关产品推荐

