我试图在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 Goyalres.data
很可能是一个对象。 - bamtheboozleres.car
而不是res.data
。 - Brian Thompson