【发布时间】:2019-08-16 18:00:08
【问题描述】:
您好,我是 React 和 Firebase 数据库的新手。尝试使用地图打印数据时出现错误。
基本上我使用的是 firebase-database,并且我已经显示了项目所有天数的列表,包括总小时数。在每一天下,我想显示工人姓名,包括当天为单个用户工作的小时数。这是屏幕截图
这是我的 Firebase 数据
正如您在数据库中看到的,在 0 键用户下给出了详细信息,但在键 1 和 2 下没有给出
现在我在尝试访问代码中给出的 row.users.map() 时打印 user_name 时遇到错误。
<Table className="MyTable">
<TableHead>
<TableRow>
<StyledTableCell>Dato</StyledTableCell>
<StyledTableCell>User Name</StyledTableCell>
<StyledTableCell align="right">Timer</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{props.data.dayWiseHours.map(row => (
<StyledTableRow key={row.date}>
<StyledTableCell component="th" scope="row">
{`${row.date}\n`}
</StyledTableCell>
<StyledTableCell component="td" scope="row">
{ row && row.users &&
row.users.map((subData, subindex) =>
<span key={subindex}>{subData.user_name}</span>
)
}
</StyledTableCell>
<StyledTableCell align="right">
{`${row.hour}\n`}
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
如果我在给定的代码下尝试它的工作正常
<TableBody>
{props.data.dayWiseHours.map(row => (
<StyledTableRow key={row.date}>
<StyledTableCell component="th" scope="row">
{`${row.date}\n`}
</StyledTableCell>
<StyledTableCell component="td" scope="row">
{ row && row.users && row.users['-LjuTOzAhVpku-hDFUJ7'].user_name ? row.users['-LjuTOzAhVpku-hDFUJ7'].user_name : "--" }
</StyledTableCell>
<StyledTableCell align="right">
{`${row.hour}\n`}
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
但密钥:row.users['-LjuTOzAhVpku-hDFUJ7'] 并不总是相同。
谢谢
【问题讨论】:
-
在我看来
row.users是一个对象而不是数组。您只能通过数组map。要迭代一个对象,您可以使用Object.keys(obj)。你能检查一下并告诉我row.users的数据类型吗? -
你是对的 row.users 是一个对象。 prntscr.com/otdngs,对不起,我没有数据库访问权限
-
问题通过 Object.keys(obj) 解决。感谢您的帮助
-
为了完整起见添加了答案。
标签: reactjs firebase firebase-realtime-database google-cloud-firestore