React渲染HTML表格:如何移除多余空<tr>元素
问题描述
我在React中基于ratings数组渲染HTML表格,使用Object.entries()遍历对象并通过.map()生成<tr>元素,但页面出现大量不需要的空<tr>。
初始代码:
{Object.entries(ratings).map((item) => { item.filter(n => n); return (item.map((Item) => { if (!Item.points === []) return (<></>); if (Item.points) { console.log(Item.points); return ( <tr key={uuidv4()}> <td>{Item.points.at(-1)}</td> </tr> ) } })) }) ?? null}
ratings数据结构:
[ { "name": "Bullet", "points": [] }, { "name": "Blitz", "points": [ [2023, 6, 4, 864], [2023, 6, 9, 1106], [2023, 6, 10, 1139], [2023, 6, 11, 1174] ] }, { "name": "Rapid", "points": [ [2023, 6, 3, 1082], [2023, 6, 4, 1035], [2023, 6, 5, 1054], [2023, 6, 6, 1081], [2023, 6, 7, 1076], [2023,6,8,1157], [2023,6,9,1131], [2023,6,10,1145], [2023,6,11,1157] ] }, { "name": "Classical", "points": [ [2023,6,9,1262] ] }, { "name": "Correspondence", "points": [] }, { "name": "Chess960", "points": [] }, { "name": "King of the Hill", "points": [] }, { "name": "Three-check", "points": [ [2023,6,5,1628] ] }, { "name": "Antichess", "points": [ [2023,6,5,1090] ] }, { "name": "Atomic", "points": [] }, { "name": "Horde", "points": [] }, { "name": "Racing Kings", "points": [] }, { "name": "Crazyhouse", "points": [] }, { "name": "Puzzles", "points": [ [2023,6,3,1353], [2023,6,4,1404], [2023,6,5,1306], [2023,6,8,1499], [2023,6,9,1514], [2023,6,10,1838], [2023,6,11,1766], [2023,6,12,1781] ] }, { "name": "UltraBullet", "points": [] } ]
尝试用length属性过滤时出现Cannot read properties of undefined (reading 'length')错误,修改后的代码无报错但未生成任何元素:
{Object.entries(ratings).map((item) => { return (Object.keys(item).filter(o => o.points?.length).map((Item) => { return ( <tr key={uuidv4()}> <td>{Item.points.at(-1)}</td> </tr> ) })) }) ?? null}
请问如何正确修改代码,移除这些多余的空<tr>元素?
解决方案
问题根源
- 错误使用
Object.entries():ratings本身是数组,无需用Object.entries()转换,直接用数组的map()遍历即可,转换后会生成[索引, 元素]的键值对数组,导致后续逻辑混乱。 - 空数组判断逻辑错误:
!Item.points === []永远为false,因为数组是引用类型,不能直接用===判断是否为空,应该用Item.points.length === 0。 - 无效过滤与遍历错误:
item.filter(n => n)未赋值给变量,等于没执行;修改后的代码中Object.keys(item)遍历的是对象的属性名(如name、points),而非数组元素本身,导致o.points不存在。
正确代码
直接遍历ratings数组,先过滤掉points为空的元素,再生成<tr>:
{ratings .filter(item => item.points?.length > 0) .map(item => ( <tr key={item.name}> <td>{item.points.at(-1)}</td> </tr> )) }
代码说明
- 过滤逻辑:用
item.points?.length > 0筛选出points不为空的元素,可选链?.避免points属性不存在时的报错。 - 元素生成:遍历过滤后的数组,每个元素直接生成对应的
<tr>,不会产生空元素。 - 键值优化:用
item.name作为key比uuidv4()更稳定,避免因uuid每次渲染生成新值导致的不必要重渲染。
内容的提问来源于stack exchange,提问作者HoodedHacker
相关产品推荐
相关产品推荐

