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

Firebase表单数据导入问题:React如何渲染数组类型字段?

解决Firebase数组字段在React中的渲染问题

问题原因

你的Voted字段是数组类型,不能直接通过.label访问,必须遍历数组中的每个元素来获取对应的label值。你之前的写法都误用了数组的操作方式,所以无法获取数据。

正确渲染方式

假设Voted数组的每个元素都包含label属性,你可以用数组的map方法遍历渲染,同时处理空数组的情况:

{info.map((infos) => (
  <tr key={infos.id}> {/* 把key移到tr上更符合React规范 */}
    <td>{infos.data.Name}</td>
    <td>{infos.data.ID}</td>
    <td>{infos.data.Email}</td>
    <td>{infos.data.Telephone}</td>
    <td>{infos.data.Branch.label}</td>
    <td>
      {/* 处理Voted数组 */}
      {infos.data.Voted?.length ? (
        infos.data.Voted.map((voteItem, idx) => (
          <span key={idx}>{voteItem.label}{idx < infos.data.Voted.length - 1 ? ', ' : ''}</span>
        ))
      ) : '无投票记录'}
    </td>
  </tr>
))}

关键说明

  • 将key放在<tr>上,避免同一列表项重复使用相同key,符合React列表渲染要求。
  • 用可选链操作符?.防止Voted为undefined时触发报错。
  • 遍历数组时给子元素加唯一key,这里用索引idx是简易方案,若数组元素有唯一ID,优先使用ID作为key。
  • 用, 分隔多个投票选项,提升页面可读性。

为什么之前的写法无效

  • infos.data.Voted.map.label:map是数组的方法,需要通过map(...)调用才能遍历数组,直接访问.label无意义。
  • infos.data.Voted.array.label:数组没有array内置属性,属于错误写法。
  • infos.data.Voted.label[Object]:语法错误,数组元素需通过索引或遍历访问,该写法不符合JavaScript语法规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:15:35