reactjs - 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)
解决方案
如果后端返回这个:
[
"User1",
"User2",
"User3"
]
然后,你会像这样渲染:
<TableBody>
{UsersRow.map(user => (
<TableRow>
<TableCell align="left">{user}</TableCell>
</TableRow>
))}
</TableBody>
上不会user
有财产row
。
推荐阅读
- java - Cucumber 将整个示例传递给一个步骤
- php - Laravel 工匠服务问题
- tensorflow - Tensorflow 对象检测 API:TensorBoard 中损坏的训练图像
- mysql - SQLSTATE [HY000]:一般错误:1030 运行迁移时出现错误 168
- json - 在 VBA 中访问 JSON 数组数据
- python - Tkinter - 使用复选框删除多条记录
- c++ - 访问作为向量索引的列表中的每个节点
- javascript - CSS / Javascript图像轮播导航按钮不起作用
- python - 如何使用烧瓶从表 sqlalchemy 中删除特定行?
- python - 多处理数组 .get_lock 可在一台计算机上运行,但不能在另一台计算机上运行