React中filter/map箭头函数报末尾需返回值错如何修复?
报错根源
你遇到的「Expected to return a value at the end of arrow function」是ESLint array-callback-return 规则的校验报错:你当前写的 filter 回调函数,只在两个条件分支下显式返回了值,只要某条数据的判断逻辑没命中这两个分支,整个箭头函数就会在无返回值的状态下走到结尾,完全不符合规则要求。之前反复调整return写法仍报错,本质是没有覆盖所有函数执行路径,始终存在走到函数末尾却没有返回值的可能。
另外要注意:filter 方法的回调设计初衷是返回布尔值来决定当前元素是否保留,你当前直接返回原数据的写法,只是靠JS的真值判断逻辑碰巧能运行,本身并不符合filter的使用规范。
具体修复步骤
- 补全所有判断分支的返回值逻辑,给没命中前置条件的场景加兜底返回值:
const items = this.state.events .filter((data) => { if (this.state.search == null) { // search为空时,保留所有数据 return true; } else if (/* 你原本写的匹配判断逻辑 */) { // 命中搜索匹配规则,保留数据 return true; } // 兜底:没命中规则的场景,显式返回false过滤掉数据 return false; }) .map((data) => { return ( <div> <span>{data.title}</span> <span>{data.description}</span> </div> ); }); - 如果不想写多层嵌套if判断,可以把过滤逻辑抽成独立的判断函数,收敛返回值逻辑,天然满足规则校验要求:
const filterEvent = (data) => { if (this.state.search == null) return true; return data.title.includes(this.state.search); } const items = this.state.events .filter(filterEvent) .map((data) => ( <div> <span>{data.title}</span> <span>{data.description}</span> </div> ));
内容的提问来源于stack exchange,提问作者Erdenedalai Mandshil
相关产品推荐
相关产品推荐

