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

在React Query分页查询中使用select选项按类别过滤图片

问题:React Query 中使用 select 选项结合 filter 过滤梗图类别

我开发了一个梗图生成器应用,客户端选择模板的路径如下:

//localhost:3001/select-template?page=${pageNumber}

数据获取代码:

const { data, isLoading, isFetching } = useQuery(
    ["images", pageNumber],
    () => fetchImages(pageNumber),
    {
      keepPreviousData: true,
      refetchOnWindowFocus: false,
      select: 'Need help with this'
    }
);

API响应格式为:

{
  all_Images: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] // 每个图片对象包含category字段
  page: "0"
  totalItems: 18
  totalPages: 2
};

首次使用React Query,希望利用select选项结合JavaScript的filter()方法,根据下拉框选中的类别展示对应图片,预期实现的示例代码如下:

select: (images) => images.filter((img) => img.category.includes(cat))

解决方案

1. 维护选中类别的状态

用React的useState存储下拉框选中的类别:

import { useState } from 'react';

const [selectedCategory, setSelectedCategory] = useState('');

2. 修正useQuery的select配置

注意API返回的是包含all_Images数组的对象,不是直接的图片数组,所以要先提取all_Images再过滤;同时把selectedCategory加入查询键,确保类别变化时自动重新计算过滤结果:

const { data, isLoading, isFetching } = useQuery(
    ["images", pageNumber, selectedCategory], // 加入selectedCategory,触发select重计算
    () => fetchImages(pageNumber),
    {
      keepPreviousData: true,
      refetchOnWindowFocus: false,
      select: (response) => {
        // 未选中类别时返回全部图片
        if (!selectedCategory) return response.all_Images;
        // 过滤出包含选中类别的图片
        return response.all_Images.filter(img => img.category.includes(selectedCategory));
      }
    }
);

3. 绑定下拉框的状态更新

给下拉框添加onChange事件,更新选中类别的状态:

<select 
  value={selectedCategory} 
  onChange={(e) => setSelectedCategory(e.target.value)}
>
  <option value="">所有类别</option>
  <option value="meme">梗图</option>
  <option value="funny">搞笑</option>
  {/* 根据你的实际类别添加选项 */}
</select>

关键说明

  • 查询键中加入selectedCategory:React Query会把这个值作为缓存依赖,当类别变化时,会基于已缓存的API响应重新执行select函数,无需再次请求API。
  • 处理空类别场景:避免用户未选择类别时出现过滤错误,直接返回全部图片。
  • 正确解析API响应:必须先从response.all_Images拿到图片数组,再执行过滤操作,这是你之前示例代码的核心问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:10:15