[英]React | TypeError: this.state.cars.map is not a function
I'm trying to show a list of car brands in react but i get this error.我正在尝试显示反应中的汽车品牌列表,但出现此错误。 The Web API is tested and works fine.
Web API 已经过测试并且工作正常。
TypeError: this.state.cars.map is not a function
类型错误:this.state.cars.map 不是函数
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>
)
}
}
Response Output响应输出
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 { … }
This error will generally crop up because you're trying to map something that is not of the type array.这个错误通常会突然出现,因为你试图映射不是数组类型的东西。 Make sure you're actually mapping an array.
确保您实际上是在映射一个数组。 If it is an array this crops up usually because the value you're expecting to map across is
undefined
or null
.如果它是一个数组,通常会出现这种情况,因为您希望映射的值是
undefined
或null
。 If that is the case, that is your problem, and you must check that the value exists before mapping it.如果是这种情况,那就是您的问题,您必须在映射之前检查该值是否存在。
In this case you're targeting res.data
which is an object, instead of the array which is res.car
.在这种情况下,您的目标是
res.data
,它是一个对象,而不是res.car
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.