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

如何在RTK Query中构建含重复过滤参数的指定格式URL?

解决RTK Query生成.NET风格重复参数URL的问题

针对后端要求的Technologies=some-id&Complexities=0&Complexities=1这种重复参数格式,RTK Query默认的参数处理无法直接生成,以下是两种可行解决思路:

思路一:自定义fetchBaseQuery的参数序列化器

通过fetchBaseQuery的paramsSerializer选项,手动控制参数的序列化逻辑,对数组类型的参数生成重复的key-value对:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const apiService = createApi({
  reducerPath: 'apiService',
  baseQuery: fetchBaseQuery({
    baseUrl: BASE_URL,
    paramsSerializer: (params) => {
      const searchParams = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        // 处理数组类型参数,逐个添加重复key
        if (Array.isArray(value)) {
          value.forEach(item => {
            searchParams.append(key, item);
          });
        } else {
          // 非数组参数正常添加
          searchParams.append(key, value);
        }
      });
      return searchParams.toString();
    }
  }),
  endpoints: (build) => ({
    getAllQuizzes: build.query<ApiResponse, QueryProps>({
      query: ({ Technologies, Complexities, page, pageSize }) => ({
        url: ENDPOINT,
        params: {
          Technologies,
          Complexities,
          page,
          pageSize, 
        }
      }),
    }),
  }),
});

思路二:在query函数中手动构建查询字符串

如果不想修改全局的baseQuery配置,可以直接在query函数里拼接完整的URL查询部分:

export const apiService = createApi({
  reducerPath: 'apiService',
  baseQuery: fetchBaseQuery({ baseUrl: BASE_URL }),
  endpoints: (build) => ({
    getAllQuizzes: build.query<ApiResponse, QueryProps>({
      query: ({ Technologies, Complexities, page, pageSize }) => {
        const searchParams = new URLSearchParams();
        // 添加Technologies数组
        if (Technologies?.length) {
          Technologies.forEach(id => searchParams.append('Technologies', id));
        }
        // 添加Complexities数组
        if (Complexities?.length) {
          Complexities.forEach(num => searchParams.append('Complexities', num.toString()));
        }
        // 添加分页参数
        searchParams.append('page', page.toString());
        searchParams.append('pageSize', pageSize.toString());
        
        return `${ENDPOINT}?${searchParams.toString()}`;
      },
    }),
  }),
});

结合MUI Async Autocomplete的处理

MUI的Async Autocomplete开启多选后(设置multiple={true}),选中的选项会以数组形式返回,刚好可以直接作为Technologies和Complexities参数传入上述的query函数,不需要额外转换。

示例代码片段:

<Autocomplete
  multiple
  options={technologiesOptions}
  renderInput={(params) => <TextField {...params} label="Technologies" />}
  onChange={(event, newValue) => {
    // newValue是选中的技术数组,直接传给RTK Query的查询参数
    dispatch(apiService.endpoints.getAllQuizzes.initiate({
      Technologies: newValue,
      Complexities: selectedComplexities,
      page: 1,
      pageSize: 3
    }));
  }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:20:40