ESLint报箭头函数末尾需返回值错误 除filter外有无其他搜索实现方式?
问题解决方案
现有filter写法修复
你遇到的ESLint报错核心是两个问题:
- filter的回调要求返回布尔值表示是否保留当前项,原代码返回
item/playlist属于隐式类型转换,逻辑不严谨,且return playlist看起来是笔误 - 当
searchTerm不为空且匹配失败的分支没有显式返回值,默认返回undefined不符合规则
修复后的写法(推荐,性能最优):
// 提前将搜索词转小写,避免每次遍历都重复转换,优化性能 const lowerSearchTerm = searchTerm.toLowerCase(); {data?.results ?.filter(item => { // 搜索词为空时保留所有项 if (searchTerm === '') { return true; } // 标题或描述匹配时保留当前项 return ( item.title.toLowerCase().includes(lowerSearchTerm) || item.description.toLowerCase().includes(lowerSearchTerm) ) }) .map((item, index) => ( <StoreItem // 建议优先用item.id作为key,而非index,避免列表重排时出现渲染异常 key={item.id ?? index} id={item.id} title={item.title} description={item.description} /> ))}
调整后所有分支都有明确的布尔返回值,ESLint报错会直接消失。
其他实现方式
1. reduce一次性完成过滤+渲染
避免两次遍历数组,适合中等数据量场景:
const lowerSearchTerm = searchTerm.toLowerCase(); {data?.results?.reduce((acc, item, index) => { const isMatch = searchTerm === '' ? true : ( item.title.toLowerCase().includes(lowerSearchTerm) || item.description.toLowerCase().includes(lowerSearchTerm) ) if (isMatch) { acc.push( <StoreItem key={item.id ?? index} id={item.id} title={item.title} description={item.description} /> ) } return acc; }, [])}
2. 前置条件分支拆分
适合小数据量场景,逻辑更直观:
const lowerSearchTerm = searchTerm.toLowerCase(); {searchTerm === '' ? data?.results?.map((item, index) => ( <StoreItem key={item.id ?? index} id={item.id} title={item.title} description={item.description} /> )) : data?.results ?.filter(item => item.title.toLowerCase().includes(lowerSearchTerm) || item.description.toLowerCase().includes(lowerSearchTerm) ) .map((item, index) => ( <StoreItem key={item.id ?? index} id={item.id} title={item.title} description={item.description} /> )) }
内容的提问来源于stack exchange,提问作者monkeys773
相关产品推荐
相关产品推荐

