You need to enable JavaScript to run this app. React中filter/map箭头函数报末尾需返回值错如何修复?
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 15:06:03