首页 > 解决方案 > Fetch Json 数据不显示

问题描述

所以我有一个函数可以返回 json 中的用户列表。我想逐个字符串打印列表,例如: User1 User2 User3 但输出什么都没有。我刚开始使用反应,有什么帮助吗?

export default function Users() {
  const classes = useStyles()
  const [UsersRow, setUsersRow] = React.useState()

  React.useEffect(() => {
    fetch("http://localhost:5000/users", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "pass " + window.localStorage.getItem("access_token"),
      },
    })
      .then(resp => {
        return resp.json()
      })
      .then(data => {
        setUsersRow(data)
      })
      .catch(error => {
        console.log(error)
        window.localStorage.removeItem("access_token")
        window.location.replace("/")
      })
  }, [])

  if (UsersRow === undefined) {
    return <div />
  }
  return (
    <div className={classes.root}>
      <h1>Users</h1>
      <Table className={classes.table} size="small">
        <TableBody>
            {UsersRow.map(row => (
            <TableRow>
              <TableCell align="left">{row.user}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}

后端函数返回一个像这样的 json:

[
  "User1", 
  "User2", 
  "User3"
]

后端功能:

@app.route('/users', methods=['GET'])
@jwt_required
def user_list():
    list_1 = []
    users = ldap.get_group_members('ship_crew')

    for user in users:
        list_1.append(str(user).split(",")[0].split("=")[1].encode())
    return jsonify(list_1)

标签: reactjs

解决方案


如果后端返回这个:

[
  "User1", 
  "User2", 
  "User3"
]

然后,你会像这样渲染:

<TableBody>
    {UsersRow.map(user => (
    <TableRow>
      <TableCell align="left">{user}</TableCell>
    </TableRow>
  ))}
</TableBody>

上不会user有财产row


推荐阅读