在对象数组中查找属性报错:无法读取undefined的'options'属性
解决"cannot read property 'options' of undefined"错误
这个错误的根源很明确:当你调用categories.find(category => category.id == setParentCategory)时,没有找到匹配的category对象,所以返回了undefined,这时候再去访问.options自然就会抛出这个报错。
常见的触发场景有两种:
setParentCategory的值和数组中所有category.id都不匹配(比如类型不匹配,比如id是数字但setParentCategory是字符串)setParentCategory的初始值是null/undefined,虽然你有setParentCategory ? ... : null的判断,但可能在某些状态切换时依然会进入find逻辑
具体解决方案
1. 给find结果加安全访问兜底
最直接的修复是使用可选链操作符?.,同时配合默认空数组,避免undefined的问题:
{setParentCategory ? <Picker selectedValue={setSubCategory} label="Year group" onChange={this.onGroupChange} options={ categories.find(category => category.id === setParentCategory)?.options || [] } /> : null}
这里的?.options会在find结果为undefined时直接返回undefined,再通过|| []给Picker一个空数组作为默认值,保证组件不会因为options为undefined而报错。
2. 确保类型严格匹配
注意你数组里的id是数字类型,如果setParentCategory是字符串类型(比如从URL参数、表单输入获取的),==的隐式转换可能偶尔失效,建议用===严格相等,并手动转换类型:
categories.find(category => category.id === Number(setParentCategory))?.options || []
3. 提前缓存查找结果(更易维护)
如果逻辑复杂,建议先把找到的category缓存下来,再做判断,代码可读性更高:
const currentCategory = categories.find(category => category.id === setParentCategory); return ( {setParentCategory && currentCategory ? <Picker selectedValue={setSubCategory} label="Year group" onChange={this.onGroupChange} options={currentCategory.options} /> : null} )
额外检查点
- 确认
setParentCategory的初始值:如果初始是0以外的数字/其他值,要确保数组里有对应的id - 可以在控制台打印
setParentCategory和categories,确认两者的匹配关系,排查是否存在值不匹配的情况
内容的提问来源于stack exchange,提问作者Bomber
相关产品推荐
相关产品推荐

