简体   繁体   中英

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.

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>
      )
  }
}

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 . 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM