React修改tableEntry.color[index]触发TypeError报错的解决方案咨询
修复方案:React状态更新导致的
map调用错误 错误原因
调用handleColor时,更新tableEntry状态只返回了color字段,完全覆盖了原状态对象,导致tableEntry.No等其他属性变为undefined,后续执行tableEntry.No.map()时触发Cannot read properties of undefined (reading 'map')错误。同时直接修改了prevState.color原数组,违反了React状态不可变原则。
修复后的handleColor函数
const handleColor = (ind, colorCheck) => { setTableEntry(prevState => { // 复制原color数组,避免直接修改原状态 const newColorArr = [...prevState.color]; // 切换目标索引的颜色值 newColorArr[ind] = colorCheck === "grey" ? "orange" : "grey"; // 返回完整的状态对象,保留所有原有属性 return { ...prevState, color: newColorArr }; }); };
额外优化:修复单选按钮互斥问题
当前代码中全局selectedValue会导致所有行的单选按钮同步选中状态,建议直接基于tableEntry.color[index]控制单选框状态,每个行使用独立的name属性:
// 替换原td内的Radio渲染逻辑 <td> <Radio value="orange" checked={tableEntry.color[index] === 'orange'} sx={{ color: grey[800], "&.Mui-checked": { color: orange[600], }, }} onClick={() => handleColor(index, tableEntry.color[index])} name={`color-radio-${index}`} /> <Radio value="grey" checked={tableEntry.color[index] === 'grey'} sx={{ color: grey[800], "&.Mui-checked": { color: grey[800], }, }} onClick={() => handleColor(index, tableEntry.color[index])} name={`color-radio-${index}`} /> </td>
内容的提问来源于stack exchange,提问作者Doctor.phil
相关产品推荐
相关产品推荐

