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

React中通过Select选项筛选contentType数组无结果问题

修复React Select组件筛选产品数组的问题

核心问题分析

你的handleContentTypeSort函数未正确实现基于contentType的过滤逻辑,导致选中选项后数据未被筛选,页面无法渲染对应内容。

具体修复步骤

  1. 修正handleContentTypeSort函数逻辑
    替换原函数为以下代码,实现选中类型的过滤,同时重置页码避免筛选后页码超出数据范围:

    const handleContentTypeSort = (e) => {
      const selectedType = e.target.value;
      setContentType(selectedType);
      // 筛选逻辑:选中"all"显示全部,否则匹配对应contentType
      const filteredData = selectedType === "all" 
        ? [...products] 
        : products.filter(item => item.contentType === selectedType);
      setFilteredProducts(filteredData);
      setCurrentPage(1);
    };
    
  2. 确保其他排序基于筛选后的数据
    价格排序等功能要使用filteredProducts而非原始products数组,保证筛选后的排序有效性:

    const handlePriceSort = (e) => {
      const sortValue = e.target.value;
      setPriceSort(sortValue);
      let sortedData = [...filteredProducts];
      if (sortValue === "asc") {
        sortedData.sort((a, b) => a.price - b.price);
      } else if (sortValue === "desc") {
        sortedData.sort((a, b) => b.price - a.price);
      }
      setFilteredProducts(sortedData);
    };
    
  3. 验证选项值与contentType匹配
    确保Select组件的选项value和产品数组中contentType的字符串完全一致(如统一小写的"article"、"video"),避免拼写或大小写不匹配导致筛选失效。

修复后效果

选中Select不同选项时,页面会立即渲染对应contentType的产品,分页和其他排序功能保持正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:10:01