You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取RTK Query中createApi最后一次查询对应的queryKey?

获取RTK Query中getUsers接口最后一次请求的queryKey并更新缓存

实现方案

RTK Query的缓存数据存储在Redux Store中,你可以通过以下步骤获取目标接口最后一次请求的queryKey并更新对应缓存:

1. 提取getUsers的所有缓存条目

直接从Store的api.queries节点中筛选出所有属于getUsers接口的缓存记录:

const storeState = store.getState();
// 筛选所有以"getUsers("开头的缓存键,对应该接口的请求记录
const getUsersCacheEntries = Object.entries(storeState.api.queries).filter(
  ([cacheKey]) => cacheKey.startsWith('getUsers(')
);

2. 定位最后一次请求的queryKey

缓存条目的requestTime字段记录了请求发起的时间戳,通过排序找到最新请求后提取queryKey:

if (getUsersCacheEntries.length === 0) return;

// 按请求时间倒序排序,取第一条即为最新请求
const latestCacheEntry = getUsersCacheEntries.sort(
  (a, b) => b[1].requestTime - a[1].requestTime
)[0];

// 从缓存键中提取queryKey(单一参数场景,复合参数需调整正则)
const latestQueryKey = latestCacheEntry[0].match(/getUsers\((.*)\)/)[1];
// 若queryKey是数字类型,需转换:const parsedKey = Number(latestQueryKey);

3. 更新对应缓存

使用updateQueryData传入获取到的最新queryKey,修改缓存数据:

api.util.updateQueryData('getUsers', latestQueryKey, (draft) => {
  // 编写缓存修改逻辑,比如新增用户、更新字段
  draft.push(newUser);
});

注意点

  • 如果getUsers的queryKey是复合类型(比如数组[page, limit]),缓存键会是getUsers([1,10])这类格式,需要调整正则匹配逻辑来正确提取。
  • 确保你的Redux Store已经正确集成了RTK Query的API reducer。

内容的提问来源于stack exchange,提问作者Dmitriy Prigulnov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 07:45:12