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

React组件中.map()函数仅迭代一次?失效问题排查

问题根源与修复方案

你的代码核心错误是遍历数组的方式完全错误:

return new Array(this.state.employees).map((_, index) => { ... })

new Array()传入数组(this.state.employees本身就是数组)时,会创建一个长度为1的新数组,唯一元素就是你的employees数组。所以map只会执行一次,index自然始终为0。


修复步骤

  1. 直接遍历原数组:删掉new Array()包裹,直接在this.state.employees上调用map,同时直接获取每个员工对象,无需通过索引从state取值,代码更简洁且避免索引错误。
  2. 添加React元素key属性:React要求列表元素必须有唯一key,用员工的employeeId作为key最合适,避免渲染警告。

修复后的完整代码:

private renderEmployeesTable() {
  if (this.state.employees) {
    return this.state.employees.map((employee) => {
      const { employeeId, name: employeeName } = employee;
      const workingHours = this.state.workingHoursForEveryEmployee.find(
        (res) => res.employeeId === employeeId
      )?.workingHours;

      return (
        <div key={employeeId} className="row">
          <div className="col">
            <p className="rowText">{employeeId}</p>
          </div>
          <div className="col">
            <p className="rowText">{employeeName}</p>
          </div>
          <div className="col">
            <p className="rowText">{workingHours}</p>
          </div>
          <div className="col">
            <p className="rowText">{this.state.hoursToWork}</p>
          </div>
        </div>
      );
    });
  }
  // 员工数据为空时的兜底渲染
  return <p>暂无员工数据</p>;
}

额外优化提示

  • 提前解构state变量,避免循环内重复访问state,提升性能:
    private renderEmployeesTable() {
      const { employees, workingHoursForEveryEmployee, hoursToWork } = this.state;
      if (employees) {
        return employees.map((employee) => {
          const { employeeId, name: employeeName } = employee;
          const workingHours = workingHoursForEveryEmployee.find(
            (res) => res.employeeId === employeeId
          )?.workingHours;
          // 后续代码不变
        });
      }
      return <p>暂无员工数据</p>;
    }
    
  • 若workingHoursForEveryEmployee数据量较大,可转成Map将find的O(n)复杂度降为O(1):
    const workingHoursMap = new Map(
      workingHoursForEveryEmployee.map(item => [item.employeeId, item.workingHours])
    );
    // 循环内直接取值
    const workingHours = workingHoursMap.get(employeeId);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:21:48