NEXTJS运行时错误:TypeError: games.map is not a function排查
问题:渲染API数据时出现
TypeError: games.map is not a function错误 我正尝试不依赖教程搭建首个展示API数据的网站,API请求已成功,控制台能打印所需数据,但渲染时出现TypeError: games.map is not a function错误。代码如下:
'use client' import React, { useEffect, useState } from 'react' export default function Home() { const [games, setGames] = useState([]) const apiKey = process.env.NEXT_PUBLIC_RAWG_API_KEY const url = `https://rawg-video-games-database.p.rapidapi.com/games?key=${apiKey}` useEffect(() => { const options = { method: 'GET', headers: { 'X-RapidAPI-Key': process.env.NEXT_PUBLIC_RAPID_API_KEY, 'X-RapidAPI-Host': 'rawg-video-games-database.p.rapidapi.com', }, } fetch(url, options) .then((response) => response.json()) .then((response) => { console.log(response.results[0]) setGames(response.results[0]) }) .catch((err) => { console.error(err) }) }, []) return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> {games && games.map((game) => { return ( <div key={game.id}> <h1>{game.name}</h1> </div> ) })} </main> ) }
错误原因
你把单个游戏对象赋值给了games状态,而map方法只能用于数组。代码中setGames(response.results[0])这一行,response.results[0]是results数组的第一个元素(单个游戏对象),但你初始化games为数组[],后续却将其改为对象类型,导致调用games.map()时出错——对象没有map方法。
解决方案
根据你的需求二选一:
展示所有游戏:将整个
results数组赋值给games
修改fetch回调里的赋值逻辑:setGames(response.results)这样
games始终保持数组类型,map方法可以正常遍历。仅展示第一个游戏:直接渲染单个对象的属性,无需使用
map
修改返回的JSX:return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> {games && ( <div key={games.id}> <h1>{games.name}</h1> </div> )} </main> )
额外提示
状态初始化时是数组类型,后续尽量保持状态类型一致,避免因类型不匹配引发的错误。
内容的提问来源于stack exchange,提问作者riccardoboe
相关产品推荐
相关产品推荐

