reactjs - 未捕获的类型错误 : map is not a function In Reactjs with Firebase

标签 reactjs firebase firebase-realtime-database google-cloud-firestore

大家好,我是 React 和 Firebase 数据库的新手。尝试使用 map 打印数据时出现错误。

SNAP01

基本上我使用的是 firebase-database,我已经显示了项目所有天数的列表,包括总小时数。在每一天,我想显示 worker 姓名,包括当天为单个用户工作的小时数。这是截图

SINGLE USER

这是我的 Firebase 数据

FIBERBASE

正如您在数据库中看到的那样,在 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 是一个 Object,您只能在 Array 上使用 map。要遍历 Object,您可以这样做:

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

Object.keys(object1).map((key) => {
  console.log('key:', key);
  console.log('value:', object1[key]);
});

首先创建对象键的数组,然后映射该数组。

关于reactjs - 未捕获的类型错误 : map is not a function In Reactjs with Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57519310/

相关文章:

reactjs -/home/Documents/node_modules/cheerio-select/lib/index.d.ts(1,15) : [0] ',' expected. TS1005 中的 TypeScript 错误

node.js - 缺少元素的 "key" Prop 。 (ReactJS 和 TypeScript)

javascript - Firebase云函数错误: Function returned undefined,预期的Promise或值

android - FirebaseRecyclerAdapter 无法将第一个布局识别为位置

javascript - 如何在几秒钟后卸载或删除 React 组件?

javascript - 安装 Babel 以与 React 和 JSX 一起使用

android - Android O 中未设置 Firebase Cloud Messaging 后台通知 channel ID

java - 我如何在此 Activity 本身中获取 firebase 数据库

java - @ServerTimestamp 在 Firebase Firestore 上始终为 null

android - 如何获取多条路径并对它们进行排序并将结果带回 firebase?