【发布时间】:2019-05-10 00:05:24
【问题描述】:
我对做出反应并尝试从 .json 文件(称为 userData.json)中获取数据非常陌生,但是即使 userData 是一个数组,.map 也无法正常工作。
我已经检查过了
console.log(Array.isArray(userData));
console.log(typeof userData);
它会回馈“真实”和“对象”。
知道我做错了什么吗? 以下是截取的全部代码:
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;
【问题讨论】:
-
result是什么? -
在我的生活中没有使用过 fetch,但显然,您正在获取 json。你不应该使用一些
.json()方法将json转换为数组吗?
标签: javascript arrays reactjs ecmascript-6 fetch