javascript - 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 查询获取的表中。
解决方案
不,RTK-Query 是文档缓存(完整响应 = 文档),而不是规范化缓存。它对缓存响应的内容及其结构一无所知——它永远不会尝试自行“缝合”其中的任何内容。
您可以通过乐观更新手动执行此操作,但 RTK-Q 自动执行的所有操作都是重新获取,这在大多数用例中应该绰绰有余。
推荐阅读
- java - 在 Google Guice 框架中使用 @Named 和 @Singleton
- ruby-on-rails - 一种形式的多个记录 - 强大的参数问题
- android - Android - 通用类作为 Kotlin 中用于改造调用的返回类型
- ksqldb - 如何在 SpringBoot 应用程序中使用 EmbeddedKsql?
- python - 有没有办法将渐变的RGB值转换为python中[0,1]内的值?
- amazon-web-services - 如果我通过 API Gateway RestAPI 将图像上传到 S3 存储桶,会产生哪些 AWS 费用?
- amazon-web-services - AWS 在 1-2 周后教育 Ec2 公钥错误?
- kubernetes - 如何在 k8s 中运行类似作业的 post-init-container
- simulation - NS2:如何为节点设置队列限制
- reporting-services - SSRS - 减少处理时间