React类组件调用两个map()时报Cannot read properties of undefined如何解决
问题原因及修复方案
报错根因
- 构造函数中
Details数组的初始化代码被注释,组件首次渲染时this.state.Details为undefined,调用.map()方法直接抛出类型错误。 - 存在隐藏风险:你当前用
Object.keys(this.state)遍历生成下拉组件,当接口请求完成后state会新增Details字段,该字段没有options属性,遍历到该字段时也会抛出异常。
修复步骤
- 取消构造函数中
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:[] // 取消注释,初始化空数组 }; }
- 修改下拉框生成逻辑,固定遍历需要生成下拉的字段,避免遍历到无关字段
// 原来的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)} /> ); })}
- 可选优化:给列表渲染添加兜底判断,避免接口返回非数组的极端情况
// 可选链写法 {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
相关产品推荐
相关产品推荐

