You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Redux Toolkit Query条件调用API,避免无效请求

解决方案:用RTK Query的skip参数实现条件请求

要解决bodyPart为"all"时触发无效API请求的问题,最直接的方式是利用RTK Query内置的skip参数控制请求是否发起,同时保留缓存特性。

具体实现步骤

  1. 在API端点定义中添加skip判断
    创建getWorkoutByBodyPart查询端点时,通过skip选项根据传入的bodyPart参数决定是否跳过请求:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const exerciseApi = createApi({
  reducerPath: 'exerciseApi',
  baseQuery: fetchBaseQuery({ baseUrl: '你的ExerciseDB API地址' }),
  endpoints: (builder) => ({
    getWorkoutByBodyPart: builder.query({
      query: (bodyPart) => ({
        url: `workouts/body-part/${bodyPart}`,
        // 正常配置非"all"时的请求参数
      }),
      // 核心逻辑:当bodyPart为"all"时跳过请求
      skip: (bodyPart) => bodyPart === 'all',
      // 跳过请求时返回默认空数组,避免数据为undefined
      transformResponse: (response) => response || [],
    }),
  }),
});

export const { useGetWorkoutByBodyPartQuery } = exerciseApi;
  1. 组件中使用时处理默认值
    调用hooks时给data设置默认空数组,保证UI渲染正常:
const { data: workouts = [] } = useGetWorkoutByBodyPartQuery(selectedBodyPart);

为什么之前的尝试无效?

你之前在query函数里返回null或Promise.resolve({ data: [] })的方式不符合RTK Query规范:

  • RTK Query的query函数期望返回请求配置对象(包含url、method等),返回null会被视为无效配置,可能仍触发错误请求逻辑;
  • query函数无需手动返回Promise,RTK Query会自动处理异步请求流程。

缓存特性的保留

使用skip参数后,RTK Query会将"all"参数对应的状态(空数组)存入缓存:

  • 再次传入"all"参数时,直接读取缓存中的空数组,不会发起新请求;
  • 参数切换为其他bodyPart时,正常发起请求并缓存结果,切换回"all"时依然读取缓存。

内容的提问来源于stack exchange,提问作者Da Moose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 08:10:22