我试图显示 react 中的汽车品牌列表,但出现此错误。 Web API 经过测试并且工作正常。
TypeError: this.state.cars.map is not a function
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
数组。
关于javascript - react | TypeError : this. state.cars.map 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825523/