未捕获的运行时错误:teams.map 不是 React 的函数

问题描述 投票:0回答:1

使用reactJS和Laravel在网站上工作,同时使用map函数从URL获取json数据,在控制台上发现此错误:

teams.map is not a function TypeError: teams.map is not a function

来自 URL 的 API json 响应:

{
"get": "teams",
"parameters": {
    "name": "manchester united"
},
"errors": [],
"results": 1,
"paging": {
    "current": 1,
    "total": 1
},
"response": [
    {
        "team": {
            "id": 33,
            "name": "Manchester United",
            "code": "MUN",
            "country": "England",
            "founded": 1878,
            "national": false,
            "logo": "https://media.api-sports.io/football/teams/33.png"
        },
        "venue": {
            "id": 556,
            "name": "Old Trafford",
            "address": "Sir Matt Busby Way",
            "city": "Manchester",
            "capacity": 76212,
            "surface": "grass",
            "image": "https://media.api-sports.io/football/venues/556.png"
        }
    }
]
}

像这样获取 json 数据:

import React, { useEffect, useState } from "react";

const TeamStats = () => {

    const [teams, setTeams] = useState([]);
  
    const getTeams = async () => {
      const response = await fetch("http://localhost:8000/home");
      const data = await response.json();
      console.log(data);
      setTeams(data);
    };
  
    useEffect(() => {
        getTeams();
    }, []);
     ....
     ....

           {teams.map(res => (
                <h4 className="text-black text-overflow">{res.response.team.name}</h4>
                ))}`

在 console.log 中发现 API 数据调用成功,但在窗口上显示数据时再次弹出错误,这是我的代码,还附加了控制台输出图像。

The console error

javascript reactjs
1个回答
0
投票

假设第一个片段中的数据结构是存储在

teams
变量中的数据结构,那么您需要在
map()
数组上调用
teams.response
,而不是直接在
teams
对象上调用。试试这个:

{
  teams.response.map(res => (
    <h4 className="text-black text-overflow">{res.team.name}</h4>
  ))
}
© www.soinside.com 2019 - 2024. All rights reserved.