无法映射对象,获取api首先返回未定义的对象

时间:2020-01-23 10:06:45

标签: reactjs

我正在获取一个api,但是我无法映射它,因为当console.log对象首先出现时,我未定义为响应,然后得到了对象。 这导致此错误Uncaught TypeError: Cannot read property 'map' of undefined。 我不知道为什么会这样,我在搜索它,但找不到解决方法。

enter image description here

我的代码:

const [UsersRow, setUsersRow] = React.useState()
  React.useEffect(() => {
    fetch("api/machine", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + window.localStorage.getItem("access_token"),
      },
    })
      .then(resp => {
        return resp.json();
      })
      .then(data1 => {
        setUsersRow(data1);
      })
      .catch(error => {

        window.localStorage.removeItem("access_token");
        window.location.replace("/");
      })

  }, []);

{console.log(UsersRow)}

  return (
    <div className={classes.root}>
      <h1>Azure machines</h1>
      <Table className={classes.table} size="small">
        <TableHead>
          <TableRow>
            <TableCell align="left">name</TableCell>
            <TableCell align="left">resource_group</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {UsersRow.map(row => (
            <TableRow key={row.name + row.resource_group}>
              <TableCell align="left" component="th" scope="row">
                <StyledButton size = "small" className={style.size3}>
                     <Link  style={{ color: 'inherit', textDecoration: 'inherit'}} to={`/machines/${row.resource_group + "/" + row.name}`}>{row.name}</Link>
                  </StyledButton>
              </TableCell>
              <TableCell align="left">{row.resource_group}</TableCell>
            </TableRow>
            ))}
        </TableBody>
      </Table>
    </div>
  )
}

2 个答案:

答案 0 :(得分:1)

这是因为您最初将UsersRow定义为undefined,以解决将此const [UsersRow, setUsersRow] = React.useState()更改为const [UsersRow, setUsersRow] = React.useState([])的问题。这会将初始状态设置为空数组。检查UsersRow的长度,然后对其执行map的功能,例如{UsersRow.length && UsersRow.map(....)}

并更改下面的代码

{UsersRow.map(row => (
            <TableRow key={row.name + row.resource_group}>
              <TableCell align="left" component="th" scope="row">
                <StyledButton size = "small" className={style.size3}>
                     <Link  style={{ color: 'inherit', textDecoration: 'inherit'}} to={`/machines/${row.resource_group + "/" + row.name}`}>{row.name}</Link>
                  </StyledButton>
              </TableCell>
              <TableCell align="left">{row.resource_group}</TableCell>
            </TableRow>
            ))}

{UsersRow.length > 0 && UsersRow.map(row => (
            <TableRow key={row.name + row.resource_group}>
              <TableCell align="left" component="th" scope="row">
                <StyledButton size = "small" className={style.size3}>
                     <Link  style={{ color: 'inherit', textDecoration: 'inherit'}} to={`/machines/${row.resource_group + "/" + row.name}`}>{row.name}</Link>
                  </StyledButton>
              </TableCell>
              <TableCell align="left">{row.resource_group}</TableCell>
            </TableRow>
            ))}

答案 1 :(得分:1)

这是因为setState不会立即反映出来,因此您最初尝试映射未定义的内容。您可以在尝试映射之前检查UsersRow变量。

<TableBody>
  {UsersRow && UsersRow.map(row => (
     <TableRow key={row.name + row.resource_group}>
        <TableCell align="left" component="th" scope="row">
          <StyledButton size = "small" className={style.size3}>
               <Link  style={{ color: 'inherit', textDecoration: 'inherit'}} to={`/machines/${row.resource_group + "/" + row.name}`}>{row.name}</Link>
           </StyledButton>
        </TableCell>
        <TableCell align="left">{row.resource_group}</TableCell>
     </TableRow>
    ))}
</TableBody>