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

如何使用React Hooks根据搜索输入值过滤重载对象数组列表

实现方案

你只需要在现有排序逻辑后新增过滤逻辑,再将最终渲染的数组替换为过滤后的结果即可,具体修改如下:

步骤1:新增搜索过滤逻辑

在你标注 // Reload the data based on the search input value.. BUT How? 的位置添加以下代码:

// 过滤匹配标题的条目,搜索为空时返回全部结果,不区分大小写
const filteredBooks = newerSorted.filter((item) => {
  if (!searchTerm) return true
  const searchVal = searchTerm.trim().toLowerCase()
  return item.title.toLowerCase().includes(searchVal)
})

步骤2:替换渲染的数组

将原来遍历 newerSorted 的部分改为遍历 filteredBooks:

{filteredBooks.map((review) => {
  const { id, title, comment, score } = review;
  return (
    <Review key={id} title={title} comment={comment} score={score} />
  );
})}

可选优化:合并冗余排序逻辑

你现有代码中三次调用sort的逻辑可以合并简化,减少不必要的计算:

// 一次完成 先按评分降序、评分相同按标题字母升序 的排序
const sortedBooks = [...combinedBooks].sort((a, b) => {
  // 先比较评分
  if (b.score !== a.score) {
    return b.score - a.score
  }
  // 评分相同再比较标题,不区分大小写
  const titleA = a.title.toLowerCase()
  const titleB = b.title.toLowerCase()
  return titleA.localeCompare(titleB)
})

替换原来的三次sort逻辑后,直接用sortedBooks做后续过滤即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:06:04