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

React类组件调用两个map()时报Cannot read properties of undefined如何解决

问题原因及修复方案

报错根因

  • 构造函数中 Details 数组的初始化代码被注释,组件首次渲染时 this.state.Details 为 undefined,调用 .map() 方法直接抛出类型错误。
  • 存在隐藏风险:你当前用 Object.keys(this.state) 遍历生成下拉组件,当接口请求完成后 state 会新增 Details 字段,该字段没有 options 属性,遍历到该字段时也会抛出异常。

修复步骤

  1. 取消构造函数中 Details 的初始化注释,确保初始值为空数组
constructor(props) {
  super(props);
  this.state = {
    years: {
      options: [
        { value: '2021', label: '2021' },
        { value: '2020', label: '2020' },
        { value: '2019', label: '2019' },
        { value: '2018', label: '2018' },
        { value: '2017', label: '2017' },
        { value: '2016', label: '2016' },
      ],
      value: null
    },
    categories: {
      options: [
          { value: '0', label: 'Incomplete' },
          { value: '1', label: '80G' },
          { value: '2', label: '80G' },
          { value: '3', label: 'Sports' },
          { value: '4', label: 'Social welfare' },
          { value: '5', label: 'Professional' },
          { value: '6', label: 'Health' },
          { value: '7', label: 'Food and Nutrition' },
          { value: '8', label: 'Education' }
      ],
      value: null
    },
    Activity: {
      options: [
        { value: '0', label :'My Causes'},
        { value: '1', label :'Liked Causes'},
        { value: '2', label :'Commented Causes'},
        { value: '3', label :'Pledged Causes'}
      ],
    value: null
    },
    Details:[] // 取消注释,初始化空数组
  };
}
  1. 修改下拉框生成逻辑,固定遍历需要生成下拉的字段,避免遍历到无关字段
// 原来的Object.keys(this.state).map 替换为下面的代码
{['years', 'categories', 'Activity'].map((name, i) => {
  return (
    <Select
      key={i}
      placeholder={name}
      options={this.state[name].options}
      onChange={this.onSelectChange.bind(this, name)}
    />
  );
})}
  1. 可选优化:给列表渲染添加兜底判断,避免接口返回非数组的极端情况
// 可选链写法
{Details?.map(emp => (
  <div> 
    <div>{emp.profile_name} </div>
  </div>
))}  

// 或者条件判断写法
{Array.isArray(Details) && Details.map(emp => (
  <div> 
    <div>{emp.profile_name} </div>
  </div>
))}  

内容的提问来源于stack exchange,提问作者Shanmugasundaram Nambusubraman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:57:04