首页 > 解决方案 > 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;

标签: javascriptarraysreactjsecmascript-6fetch

解决方案


但是即使 userData 是一个数组, .map 也不起作用。

render()被叫了两次。第一次,初始状态被渲染,userData是一个空数组,你得出的结论userData是一个数组。这一次,映射不会失败。现在数据被获取,并且您作为响应对象调用setStateuserData这就是fetch()解析为),这一次,Array.isArray将返回false(但您不知何故没有看到),并且.map不存在。

要解析fetch调用结果并获取数组,请使用.json()

 fetch("../data/userData.json")
   .then(res => res.json())
   .then(result => /*...*/)

推荐阅读