首页 > 解决方案 > Redux RTK Query:仅使列表中的单个元素无效

问题描述

我为 RTK 查询定义了以下 API:

export const postsApi = createApi({
  reducerPath: "postsApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://myservice.co/api/v2/' }),
  tagTypes: ["Posts"],
  endpoints: (builder) => ({
    getAllPosts: builder.query({
      query: () => ({ method: "GET", url: "/posts" }),
      transformResponse: (response) => response.posts,
      providesTags: (result) =>
        result
          ? [
              ...result.map(({ id }) => ({ type: "Posts", id })),
              { type: "Posts", id: "LIST" },
            ]
          : [{ type: "Posts", id: "LIST" }],
    }),
    updatePost: builder.mutation({
      query: ({ postId, ...body }) => ({
        url: `/posts/${postId}`,
        method: "POST",
        config: { body },
      }),
      invalidatesTags: (_, __, arg) => [{ type: "Posts", id: arg.id }],
    }),
    getPost: builder.query({
      query: (postId) => ({
        method: "GET",
        url: `/posts/${postId}`,
      }),
      providesTags: (_, __, id) => [{ type: "Posts", id }],
    }),
  }),
});

export const { useGetAllPostsQuery, useUpdatePostMutation, useGetPostQuery } = postsApi;

我想做的是,当成功调用 updatePost 时,它只会使单个帖子的缓存无效,并使用 getPost 查询而不是 getAllPosts 重新获取信息。这有可能吗?这些帖子显示在使用 getAllPosts 查询获取的表中。

标签: javascriptreduxreact-reduxrtk-query

解决方案


不,RTK-Query 是文档缓存(完整响应 = 文档),而不是规范化缓存。它对缓存响应的内容及其结构一无所知——它永远不会尝试自行“缝合”其中的任何内容。

您可以通过乐观更新手动执行此操作,但 RTK-Q 自动执行的所有操作都是重新获取,这在大多数用例中应该绰绰有余。


推荐阅读