NEXTJS未处理的运行时错误TypeError:games.map不是函数

ngynwnxp  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(79)

我正在尝试建立我的第一个网站,显示数据从一个API没有教程。我错过了什么吗?
我正确地获取了API,控制台日志打印了我需要的数据,但当我试图显示它时,它给了我games.map不是函数错误。

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

kuuvgm7e1#

当数据不是数组时会发生此错误,并且在此示例中,数据(response.results[0])很有可能是对象而不是数组。

相关问题