ReactJS页面无数据渲染异常:控制台有数据但界面不显示
问题分析与解决方法
核心问题
你的代码存在两个关键语法错误,导致JSX无法被正确返回和渲染:
- 外层
map未返回内部元素集合:Object.keys(categorizedDataFoods2).map的回调函数里,你直接执行了内部的uniquePackingLocationsF.map,但没有将其作为返回值返回,React无法获取到要渲染的元素。 - 内部
map被多余的大括号包裹:{uniquePackingLocationsF.map(...)}这里的大括号会被解析为JavaScript块级作用域,而非JSX表达式的一部分,导致内部生成的Table元素无法被识别。
修正后的代码
{Object.keys(categorizedDataFoods2).map((key, index) => { const uniquePackingLocationsF = [...new Set(categorizedDataFoods2[key]?.items.sort((a, b) => a.packingLocation.localeCompare(b.packingLocation)).map(item => item.packingLocation))]; // 去掉多余大括号,并且将内部map的结果作为外层map的返回值 return uniquePackingLocationsF.map((location) => { const filteredItemsF = categorizedDataFoods2[key]?.items.filter(item => item.packingLocation === location); return ( <Table className="finallist" key={location}> <TableHead> <TableRow> <TableCell><b style={{textTransform:'uppercase'}}>FOOD</b></TableCell> <TableCell></TableCell> </TableRow> </TableHead> <TableBody> {filteredItemsF.map((item, index) => ( <TableRow key={index}> <TableCell>{item.Category}</TableCell> <TableCell>{item.Quantity} x {item.Name}</TableCell> </TableRow> ))} </TableBody> </Table> ); }); })}
关键修改点说明
- 在外层
map的回调中添加return关键字,将内部uniquePackingLocationsF.map生成的JSX数组返回给外层map,确保React能收集所有要渲染的Table元素。 - 移除内部
uniquePackingLocationsF.map外层的多余大括号,避免将其解析为块级作用域,让内部生成的JSX元素被正确识别为返回值。 - 额外优化:将内层
filteredItemsF.map的箭头函数改为简洁写法(去掉多余的return和大括号),简化代码结构。
验证方法
修改后可以先尝试返回简单字符串测试,比如将内部返回的Table替换为return <div>{location}</div>,确认页面能正常渲染后再恢复原Table代码。
内容的提问来源于stack exchange,提问作者Paul VI
相关产品推荐
相关产品推荐

