React中使用Map报错Cannot read properties of undefined排查
问题排查与修复
核心错误原因
undefined reading map报错根源:- 定义
createCellsForRow时没有做入参兜底,当传入的cells为undefined时,直接调用.map()必然触发类型错误 - 提供的mock数据每条记录只有
SNO、SregID、Status三个属性,根本不存在cells字段,rowData.cells取出来本身就是undefined,和“有没有拿到整体数据”没有关系
- 定义
cells is not defined引用错误根源:
把条件判断写在了函数定义的外层,const createCellsForRow = cells.length > 0 ? 函数 : null这行代码执行时,当前作用域根本没有声明cells变量,自然抛引用错误。入参校验逻辑必须写在函数体内部。
修复代码
1. 修正createCellsForRow,加入参兜底逻辑
const createCell = cell => ({ key: cell.key, children: cell.title }); // 入参不存在/非数组时直接返回null,符合需求 const createCellsForRow = (cells) => { if (!Array.isArray(cells)) return null; return cells.map(cell => createCell(cell)); };
2. 修正数据映射逻辑,匹配Table组件要求的结构
现有mock数据结构和组件要求的行数据结构完全不匹配,要么调整mock数据,要么在遍历的时候做字段转换,示例如下:
const StTable = () => { // selectedKey存单个行的key,初始值不要用空数组,改成null即可 const [selectedKey, setSelectedKey] = useState(null); const handleRowToggle = (event, metaData) => { event.preventDefault(); if (selectedKey !== metaData.key) { setSelectedKey(metaData.key); } }; const createRow = (rowData, index) => { // 把mock原始字段映射成组件要求的cells数组结构,凑够4列 const formattedCells = [ { key: `cell-${index}-0`, title: rowData.SNO }, { key: `cell-${index}-1`, title: rowData.SregID }, { key: `cell-${index}-2`, title: rowData.Status }, { key: `cell-${index}-3`, title: '-' } ]; return { key: `row-${index}`, cells: createCellsForRow(formattedCells), toggleAction: { metaData: { key: `row-${index}` }, onToggle: handleRowToggle, isToggled: selectedKey === `row-${index}`, toggleLabel: '操作', // 原mock无toggleText字段,可按需替换 }, }; }; // 给createRows也加层兜底,防止mockData本身异常 const createRows = (data) => { if (!Array.isArray(data)) return []; return data.map((childItem, index) => createRow(childItem, index)); }; return ( <Table summaryId="example-single-select" summary="This table shows an implementation of single row selection." numberOfColumns={4} cellPaddingStyle="standard" rowStyle="toggle" dividerStyle="horizontal" headerData={{ selectAllColumn: { checkLabel: 'Single Selection', }, cells: [ { key: 'cell-0', id: 'toggle-0', children: 'Name' }, { key: 'cell-1', id: 'toggle-1', children: 'Address' }, { key: 'cell-2', id: 'toggle-2', children: 'Phone Number' }, { key: 'cell-3', id: 'toggle-3', children: 'Email Id' }, ], }} bodyData={[ { rows: createRows(mockData), }, ]} /> ); }; export default StTable;
额外注意
mock数据里SNO字段写的001、002这类前缀带0的数字,在JS里会被自动转成八进制数值,建议改成字符串格式避免解析异常:
const mockData = [ {"SNO":"001", "SregID":"SOO1", "Status": "Available"}, {"SNO":"002", "SregID":"SOO2", "Status": "Not Available"}, {"SNO":"003", "SregID":"SOO3", "Status": "Available"}, ]
内容的提问来源于stack exchange,提问作者dev_to_be
相关产品推荐
相关产品推荐

