ReactJS报错:Cannot convert undefined or null to object 问题解决
问题解决:Cannot convert undefined or null to object 错误修复
你的报错根源在于newata?.GearCategories可能是undefined/null,或者它的属性值里存在undefined,导致Object.values()无法处理非对象参数,同时过滤逻辑也没跳过无效的chunk项。以下是具体修复方案:
核心修改点
- 确保
Object.values()的参数始终是有效对象:用空值合并运算符??兜底空值 - 过滤掉
chunk为undefined的无效项 - 安全获取
label,避免数组为空时触发报错
修改后的代码
const categorizedDatas2 = maam.reduce((acc, curr) => { const { id, Category, CategoryId, SubCategory, SubCategoryId, Name, Brand, Owner, RealOwner, packingLocation, Quantity, Weight, Status } = curr; // 兜底空值,确保Object.values始终接收对象参数 const categoryValues = Object.values(newata?.GearCategories ?? {}); // 先过滤undefined的chunk,再匹配CategoryId const categorymatch = categoryValues.filter(chunk => chunk && chunk.id === CategoryId); // 用可选链安全获取label,防止数组为空时报错 const realcat = categorymatch[0]?.label; if (!acc[Owner]) { acc[Owner] = { items: [], }; } acc[Owner].items.push({ id, Category, CategoryId, SubCategory, SubCategoryId, Name, Brand, Owner, RealOwner, packingLocation, Quantity, Weight, Status }); return acc; }, {});
额外补充
如果业务需要realcat不能为undefined,可以给它设置默认值:
const realcat = categorymatch[0]?.label ?? '未分类';
内容的提问来源于stack exchange,提问作者Paul VI
相关产品推荐
相关产品推荐

