You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用map函数访问嵌套对象的数组属性并渲染表格?

问题解决:渲染MongoDB返回的数组属性到表格

你现在的核心问题是把整个响应对象当成了数组处理,但实际要遍历的是对象里的lights数组属性,按以下方式修改代码即可:

修正步骤

  1. 先明确你的数据结构:控制台输出的对象应该是类似这样的结构:
{
  lights: [
    { _id: "xxx", name: "灯光1", status: "开启" },
    { _id: "yyy", name: "灯光2", status: "关闭" }
  ]
}

你需要先取出对象中的lights数组,而不是直接用整个对象判断。

  1. 修改渲染代码:
// 假设你从后端拿到的数据存在变量data中
{Array.isArray(data.lights)
  ? data.lights.map((light) => (
      <TableRow
        key={light._id} // 优先用MongoDB文档的_id作为key,比index更可靠
        sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
      >
        <TableCell>{light.name}</TableCell>
        <TableCell>{light.status}</TableCell>
      </TableRow>
    ))
  : <TableRow><TableCell colSpan={2}>暂无灯光数据</TableCell></TableRow>
}

关键说明

  • 移除了多余的Object.values(lights):因为data.lights本身就是数组,直接用map遍历即可,Object.values是用来处理普通对象的。
  • 替换key为light._id:用MongoDB自动生成的唯一ID作为key,避免使用索引可能导致的渲染异常问题。
  • 增加了无数据时的兜底显示,提升用户体验。

内容的提问来源于stack exchange,提问作者Anushka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:02:54