如何在Redux Toolkit中间件中捕获RTK Query的fulfilled动作?
问题描述
我希望在某个RTKQ查询完成后触发副作用,通过中间件实现,但当前的实现依赖硬编码字符串判断action类型和端点名称,感觉很粗糙:
const recreateTransferOnAppStartMiddleware: Middleware<unknown, RootState> = storeApi => next => action => { const isFulfilledAction = action.type === `api/executeQuery/fulfilled`; const isGetUserAction = action.meta && action.meta.arg && action.meta.arg.endpointName === `getUser`; if (isFulfilledAction && isGetUserAction) recreateTransfers(storeApi); return next(action); };
改进方案
方法1:使用RTKQ生成的matchFulfilled匹配器
RTKQ为每个定义的端点自动生成matchFulfilled方法,可直接用来判断动作是否是该端点的成功响应,彻底避免硬编码字符串。
假设你的API切片定义如下:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; export const apiSlice = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ baseUrl: '/' }), endpoints: (builder) => ({ getUser: builder.query({ query: (id) => `/users/${id}`, }), }), }); // 导出端点的匹配器 export const { endpoints: { getUser } } = apiSlice;
修改后的中间件代码:
const recreateTransferOnAppStartMiddleware: Middleware<unknown, RootState> = storeApi => next => action => { if (getUser.matchFulfilled(action)) { recreateTransfers(storeApi); } return next(action); };
方法2:用isAnyOf组合多个端点匹配器
如果需要同时监听多个端点的成功动作,可以用Redux Toolkit的isAnyOf工具函数组合多个matchFulfilled:
import { isAnyOf } from '@reduxjs/toolkit'; import { apiSlice } from './path-to-api-slice'; const { getUser, getProfile } = apiSlice.endpoints; const recreateTransferOnAppStartMiddleware: Middleware<unknown, RootState> = storeApi => next => action => { if (isAnyOf(getUser.matchFulfilled, getProfile.matchFulfilled)(action)) { recreateTransfers(storeApi); } return next(action); };
优势说明
- 彻底消除硬编码字符串,避免拼写错误
- 类型安全:TypeScript会自动校验动作类型,减少运行时错误
- 代码更简洁易读,后续维护成本更低
内容的提问来源于stack exchange,提问作者Rychu
相关产品推荐
相关产品推荐

