系列文章:
RTK Qurey+TypeScript基本使用(一):查询与添加数据
RTK Qurey+TypeScript基本使用(二):缓存刷新
前言
我们前面使用的缓存刷新,是先让本地缓存失效,然后去服务端获取新的数据。而一些小的操作没有必要重新去获取服务端的新数据,我们只需要向服务端发送更新的数据,并直接将本地缓存修改为对应的数据就行。
我们先提前定义下数据类型:
// dataType/IReaction.tsx
interface IReaction {
[key: string]: number
}
export default IReaction;
// dataType/IPostState.tsx
import IReaction from "./IReaction";
interface IPostState {
id: string;
title: string;
content: string;
user: string;
date: string;
reactions?: IReaction
}
export default IPostState;
修改本地缓存
// redux/apiSlice.tsx
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import IPostState from '../dataType/IPostState'
export const apiSlice = createApi({
reducerPath: 'baseapi',
// 查询基础路径
baseQuery: fetchBaseQuery({ baseUrl: 'http://127.0.0.1:8780/fakeApi' }),
endpoints: builder => ({
//查询所有数据
// getPosts这个名字是自己起的,叫啥都行
// < >里面的泛型,第一个是请求返回数据的类型,第二个接收参数的数据类型
getPosts: builder.query<IPostState[], void>({
query: () => '/posts',
}),
addReaction: builder.mutation<any, { postId: string, reactionName: string }>({
query: ({ postId, reactionName }) => ({
url: `addreaction?id=${postId}`,
method: 'POST',
body: { reactionName }
}),
// 修改本地缓存
// `updateQueryData` 需要请求接口名称和缓存键参数, 所以它知道要更新哪一块缓存状态
async onQueryStarted({ postId, reactionName }, { dispatch, queryFulfilled }) {
const patchResult = dispatch(
apiSlice.util.updateQueryData('getPosts', undefined, draft => {
//这里开始写你要修改的缓存
const post = draft.find((post: IPostState) => post.id === postId)
if (post) {
if (post.reactions) {
post.reactions[reactionName] = post.reactions[reactionName] + 1
}
}
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()
}
}
})
})
})
// 导出的方法必须是 use...Query 或 use...Mutation
// ... 为上面自定义的名字
export const {
useGetPostsQuery,
useAddReactionMutation
} = apiSlice