[英]React TypeError: this.state.descriptions.map is not a function
[英]React | TypeError: this.state.cars.map is not a function
我正在尝试显示反应中的汽车品牌列表,但出现此错误。 Web API 已经过测试并且工作正常。
类型错误: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>
)
}
}
响应输出
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 { … }
这个错误通常会突然出现,因为你试图映射不是数组类型的东西。 确保您实际上是在映射一个数组。 如果它是一个数组,通常会出现这种情况,因为您希望映射的值是undefined
或null
。 如果是这种情况,那就是您的问题,您必须在映射之前检查该值是否存在。
在这种情况下,您的目标是res.data
,它是一个对象,而不是res.car
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.