【问题标题】:React | TypeError: this.state.cars.map is not a function反应 | TypeError:this.state.cars.map 不是函数
【发布时间】:2020-01-20 22:53:29
【问题描述】:

我试图在 react 中显示汽车品牌列表,但出现此错误。 Web API 已经过测试并且工作正常。

TypeError: 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 { … }

【问题讨论】:

  • 你能分享一下你在res变量中得到了什么吗?
  • res.data 很可能是一个对象
  • 看起来您可能需要将其设置为 res.car 而不是 res.data
  • 是json对象
  • 你能分享一下 res.data 的样子吗

标签: javascript reactjs


【解决方案1】:

通常会出现此错误,因为您正在尝试映射不属于数组类型的内容。确保您实际上正在映射一个数组。如果它是一个数组,通常会出现这种情况,因为您希望映射的值是 undefinednull。如果是这种情况,那就是您的问题,您必须在映射之前检查该值是否存在。

在这种情况下,您的目标是 res.data,它是一个对象,而不是 res.car 的数组。

【讨论】:

  • 在他的情况下实际上是res.car
  • 很好看的@DragoşPaulMarinescu
猜你喜欢
  • 2021-01-04
  • 2017-01-28
  • 2019-08-03
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 2020-10-12
相关资源
最近更新 更多