如何使用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
相关产品推荐
相关产品推荐

