javascript - TypeError: userData.map is not a function even though userData is an array
问题描述
I am quite new to react and trying to fetch data from a .json file (called userData.json), but .map is not working even though userData is an array.
I already checked this by doing
console.log(Array.isArray(userData));
console.log(typeof userData);
and it's giving back 'true' and 'object'.
Any idea what I am doing wrong? Here is the whole code snipped:
import React from "react";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
class JsonTable extends React.Component {
constructor(props) {
super(props);
this.state = {
userData: [],
error: undefined
};
}
componentDidMount() {
fetch("../data/userData.json").then(
result => {
this.setState({
userData: result
});
},
error => {
this.setState({ error });
}
);
}
render() {
const { userData } = this.state;
console.log(Array.isArray(userData));
console.log(typeof userData);
return (
<Paper>
<Table>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Foto</TableCell>
<TableCell>Kategorie</TableCell>
<TableCell>Kontaktinformation</TableCell>
<TableCell>Job</TableCell>
<TableCell>Notiz</TableCell>
</TableRow>
</TableHead>
<TableBody>
{userData.map(row => {
return (
<TableRow key={row.id}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell>{row.image}</TableCell>
<TableCell>{row.category}</TableCell>
<TableCell>{row.contactInfo}</TableCell>
<TableCell>{row.job}</TableCell>
<TableCell>{row.note}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Paper>
);
}
}
export default JsonTable;
解决方案
但是即使 userData 是一个数组, .map 也不起作用。
号render()
被叫了两次。第一次,初始状态被渲染,userData
是一个空数组,你得出的结论userData
是一个数组。这一次,映射不会失败。现在数据被获取,并且您作为响应对象调用setState
(userData
这就是fetch()
解析为),这一次,Array.isArray
将返回false
(但您不知何故没有看到),并且.map
不存在。
要解析fetch
调用结果并获取数组,请使用.json()
:
fetch("../data/userData.json")
.then(res => res.json())
.then(result => /*...*/)
推荐阅读
- android - 无法设置自定义按钮的样式
- javascript - React dropzone: useState, async inside onDropAccepted
- ios - 如何裁剪具有 10 像素偏移的图像?
- javascript - Association.js:39 未捕获的类型错误:无法读取未定义的属性“classList”
- php - php工匠迁移失败
- mysql - 如何在 grafana 查询中使用累积求和变量?
- scala - Scala bazel Worker 进程没有返回 WorkResponse:
- typescript - Javascript 需要 Typescript 导入
- windows - 通过 GUI 时间线 Windows 窗体 C# 控制值
- c++ - 如何将 char 数组声明为函数参数?或者告诉我这段代码还有其他问题?