如何在RTK Query中强制删除指定Key的缓存数据?
RTK Query 实现特定缓存Key的硬失效方案
RTK Query 默认的 invalidateTags 属于软失效:标记缓存为过期,但仍保留旧数据供页面展示,同时后台静默重新获取数据,这就导致页面只会显示 isFetching: true 而非 isLoading: true,存在旧数据误导用户的风险。
要实现针对特定Key的硬失效(直接删除对应缓存,触发页面进入加载状态),可以通过以下方式:
方法:使用 cache.removeQueries 手动删除指定缓存
在mutation的onSuccess回调中,调用RTK Query提供的cache.removeQueries方法,精准删除目标查询的缓存。
示例代码
假设你有获取实体详情的查询getEntityDetail,以及修改实体的mutationupdateEntity:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; const entityApi = createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/api' }), endpoints: (builder) => ({ // 获取实体详情的查询 getEntityDetail: builder.query({ query: (entityId) => `/entities/${entityId}`, // 为该查询标记带ID的标签,方便后续精准匹配 providesTags: (result, error, entityId) => [{ type: 'Entity', id: entityId }] }), // 修改实体的mutation updateEntity: builder.mutation({ query: ({ id, data }) => ({ url: `/entities/${id}`, method: 'PUT', body: data }), async onSuccess(_, { id }, { cache }) { // 方式1:通过queryKey删除指定缓存 await cache.removeQueries({ queryKey: ['getEntityDetail', id] }); // 方式2:通过标签删除指定缓存(需与providesTags定义匹配) // await cache.removeQueries({ type: 'Entity', id }); } }) }) }); export const { useGetEntityDetailQuery, useUpdateEntityMutation } = entityApi;
效果说明
执行updateEntity mutation成功后,对应实体详情的缓存会被直接删除。当用户回到详情页时,useGetEntityDetailQuery会重新发起请求,此时isLoading会变为true,页面可以展示加载状态,直到新数据获取完成,彻底避免旧过期数据的展示。
匹配规则说明
cache.removeQueries支持多种匹配条件:
queryKey:精准匹配查询的唯一标识(比如['getEntityDetail', 123])tags:匹配查询标记的标签(比如{ type: 'Entity', id: 123 })endpointName:匹配指定的查询端点(比如'getEntityDetail',会删除该端点下所有缓存)
根据你的需求选择最精准的匹配方式即可。
内容的提问来源于stack exchange,提问作者Probosckie
相关产品推荐
相关产品推荐

