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

如何为单个数组同时应用分类与国家双过滤器?

解决方案:实现多条件组合过滤

你的核心问题是每次过滤都直接基于原始数据loadData,覆盖了之前的过滤结果,导致无法同时生效多个筛选条件。要实现分类+国家的交集筛选,需要把所有过滤条件都存在状态里,然后统一执行组合过滤逻辑。

具体修改步骤:

  • 新增状态保存当前的国家和分类过滤值
  • 编写一个统一的过滤函数,根据所有条件(搜索词、国家、分类)组合筛选原始数据
  • 各个筛选控件只更新对应状态,触发统一过滤

修改后的代码示例:

const loadData = props.load 
// 新增两个状态保存当前的过滤条件
const [card, setCard] = useState(loadData)
const [searchPhrase, setSearchPhrase] = useState("")
const [selectedCountry, setSelectedCountry] = useState("")
const [selectedCategory, setSelectedCategory] = useState("")

// 统一的过滤函数,组合所有条件
const filterData = () => {
  let filtered = [...loadData]
  
  // 应用搜索词过滤
  if (searchPhrase) {
    filtered = filtered.filter(card => 
      card.title.toLowerCase().includes(searchPhrase.toLowerCase())
    )
  }
  
  // 应用国家过滤
  if (selectedCountry) {
    filtered = filtered.filter(card => 
      card.country.includes(selectedCountry)
    )
  }
  
  // 应用分类过滤
  if (selectedCategory) {
    filtered = filtered.filter(card => 
      card.cat.includes(selectedCategory)
    )
  }
  
  setCard(filtered)
}

// 搜索输入只更新状态,然后调用统一过滤
const handleSearchChange = (event)=>{
  setSearchPhrase(event.target.value)
  filterData()
}

// 国家选择只更新状态,然后调用统一过滤
const handleCountryChange = (event)=>{
  setSelectedCountry(event.target.value)
  filterData()
}

// 分类选择只更新状态,然后调用统一过滤
const handleCategoryChange = (event)=>{
  setSelectedCategory(event.target.value)
  filterData()
}

代码说明:

  • 所有筛选条件(搜索词、国家、分类)都存在独立状态中,不会互相覆盖
  • filterData函数会依次应用所有非空的筛选条件,最终得到所有条件的交集结果
  • 每个筛选控件的事件处理函数只负责更新对应状态,然后触发统一的过滤逻辑
  • 如果需要清空某个条件,只需将对应状态设为空字符串,filterData会自动忽略空条件

这样就能实现你想要的「分类为SaaS且国家为新加坡」的交集筛选效果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:40:35