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

React中如何基于多个分类key对map渲染的博客文章进行过滤

博客分类多选筛选实现方案

第一步:修正复选框状态更新逻辑

原代码取消勾选时直接修改state原数组,不符合React不可变更新原则,会导致状态变更不触发组件重渲染,调整handleCheckbox方法如下:

const handleCheckbox = event => {
  const targetId = event.target.value
  if (event.target.checked) {
    setFilterArray(prev => [...prev, targetId])
  } else {
    // 用filter返回新数组,不修改原state
    setFilterArray(prev => prev.filter(id => id !== targetId))
  }
}

第二步:新增文章过滤逻辑

在return之前添加过滤逻辑,根据选中的分类ID筛选符合要求的文章:

// 筛选后的文章列表
const filteredPosts = data.allSanityPost.edges.filter(postItem => {
  // 没有选中任何分类时,返回所有文章
  if (filterArray.length === 0) return true
  // 拿到当前文章的所有分类ID
  const postCategoryIds = postItem.node.categories.map(cate => cate.id)
  // 或逻辑:只要文章归属任意一个选中的分类,就保留(绝大多数筛选场景用这个)
  return filterArray.some(selectedId => postCategoryIds.includes(selectedId))
  // 如果你需要与逻辑:文章必须同时归属所有选中的分类才保留,把上面的return替换成下面这行
  // return filterArray.every(selectedId => postCategoryIds.includes(selectedId))
})

第三步:替换渲染的数据源

把原来渲染文章部分的数据源从data.allSanityPost.edges换成我们计算好的filteredPosts即可:

<div className="flex flex-wrap">
  {filteredPosts &&
    filteredPosts.map((postItem, i) => (
        <PreviewPost key={postItem.node._id} sanityData={postItem}></PreviewPost>
    ))}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:48:04