JS开发饼图触发TypeError: Cannot read properties of undefined (reading 'reduce')如何解决
错误根因
该报错的核心原因是执行reduce方法的slices变量值为undefined,仅数组类型拥有reduce实例方法,undefined或非数组类型调用该方法就会触发该异常。
排查修复方案
- 第一步检查props传入逻辑:你调用
renderPaths时传入的参数是this.props.slices,先确认父组件是否正确传递了slices字段、字段名是否拼写正确、是否存在异步请求还未拿到数据就调用渲染方法的场景。 - 第二步给入参加默认值兜底:在
renderPaths函数的参数位置直接设置默认空数组,避免入参为空的情况:
// 函数参数加默认值,同时加类型校验 function renderPaths(slices = []) { // 非数组类型直接返回,避免异常 if (!Array.isArray(slices)) return null // 原有逻辑保持不变 const total = slices.reduce((totalValue, value) => totalValue + value, 0); if (value === total) { return ( <circle r={radius} cx={center} cy={center} fill={color} key={index} /> ); } if (value === 0) { return; } const valuePercentage = value / total; const longArc = valuePercentage <= 0.5 ? 0 : 1; radSegment += valuePercentage * radCircumference; const nextX = Math.cos(radSegment) * radius; const nextY = Math.sin(radSegment) * radius; // 剩余原有逻辑... }
补充优化建议
如果slices数组中的元素存在非数字类型的可能,可以修改reduce逻辑做类型兼容,避免累加结果为NaN影响后续百分比计算:
const total = slices.reduce((totalValue, value) => totalValue + Number(value || 0), 0);
内容的提问来源于stack exchange,提问作者Subba Reddy
相关产品推荐
相关产品推荐

