React报错Cannot read properties of undefined (reading 'id')求助
解决项目卡片样式切换时的"Cannot read property 'active' of undefined"错误
问题根源
你的代码中style.find((styles) => styles.id === card.id)可能返回undefined——当某个card.id在style数组中找不到对应的匹配项时,find方法就会返回undefined,此时直接访问.active就会触发"Cannot read property 'active' of undefined"错误。哪怕你通过VS Code hover能看到数组有数据,也可能存在个别卡片的id与样式数组的id不匹配的情况。
解决方案
以下几种方式可以解决这个问题:
使用可选链操作符(推荐):
在访问active属性前添加?.,如果find返回undefined,会直接短路,避免报错:<div className={`${style.find((styles) => styles.id === card.id)?.active ? 'description-on' : 'description-off'}`}>提前兜底处理匹配结果:
先获取匹配的样式对象,若找不到则使用默认值:const matchedStyle = style.find((styles) => styles.id === card.id) || { active: false }; <div className={`${matchedStyle.active ? 'description-on' : 'description-off'}`}>排查数据源匹配问题:
打印所有卡片的id和样式数组的id列表,确认是否存在不匹配的项,从根源避免找不到的情况:console.log('Card IDs:', cards.map(card => card.id)); console.log('Style IDs:', style.map(s => s.id));
内容的提问来源于stack exchange,提问作者Moonlight
相关产品推荐
相关产品推荐

