React | TypeError: this.state.cars.map不是一个函数。

3
我试图在React中显示汽车品牌列表,但是出现了以下错误:“TypeError: this.state.cars.map不是一个函数”。Web API经过测试,工作正常。
import React from "react";
import axios from "axios";

export default class cars extends React.Component {
  state = {
    cars: []
  };

  async componentDidMount() {
    axios.get("http://localhost:3000/api/fetchcars").then(res =>{
        console.log(res);
        this.setState({cars: res.data});
    });
  }

  render() {
      return(
          <ul>
              {this.state.cars.map(car => <li>{car.brand}</li>)}
          </ul>
      )
  }
}

响应输出

config: Object { url: "http://localhost:3000/api/fetchcars", method: "get", timeout: 0,  }
data: {}
car: Array(3) [ {}, {}, {} ]
status: true
<prototype>: Object {  }
headers: Object { "content-type": "application/json; charset=utf-8" }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false,  }
status: 200
statusText: "OK"
<prototype>: Object {  }

你能分享一下 res 变量里面的内容吗? - Nikhil Goyal
1
res.data 很可能是一个对象。 - bamtheboozle
看起来你可能需要将它设置为 res.car 而不是 res.data - Brian Thompson
这是JSON对象。 - Kaiison
@BrianThompson 仍然是同样的问题。 - Kaiison
显示剩余6条评论
1个回答

1
这个错误通常会出现,是因为您试图映射的内容不是数组类型。确保您实际上正在映射一个数组。如果它是一个数组,那么通常是因为您期望映射的值是 undefinednull。如果是这种情况,那么这就是您的问题,您必须在映射之前检查该值是否存在。
在这种情况下,您的目标是 res.data,它是一个对象,而不是数组,数组是 res.car

在这种情况下,实际上是 res.car - bamtheboozle
很好地发现了@DragoşPaulMarinescu - William Park

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接