【问题标题】:Concatenate data from multiple fetch JS (RAWG API)连接来自多个 fetch JS (RAWG API) 的数据
【发布时间】:2021-07-18 20:27:53
【问题描述】:

我正在尝试建立一个显示游戏和详细信息的网站,我在 google 上搜索并找到了 RAWG Api,它们提供了一个公共 API 来获取超过 500k 的游戏数据。

他们提供的结果是这样的:

{
"count": 0,
"next": "http://example.com",
"previous": "http://example.com",
"results": [
{
"id": 0,
"slug": "string",
"name": "string",
"released": "2021-07-18",
"tba": true,
"background_image": "http://example.com",
"rating": 0,
"rating_top": 0,
"ratings": { },
"ratings_count": 0,
"reviews_text_count": "string",
"added": 0,
"added_by_status": { },
"metacritic": 0,
"playtime": 0,
"suggestions_count": 0,
"updated": "2021-07-18T11:39:53Z",
"esrb_rating": {},
"platforms": []
}
]
}

这意味着响应仅限于 20 个结果,但它们还提供了一个下一个链接来获取其余数据。

问题是,我试图一次获取所有数据并将其显示在一个页面中,我正在使用 NextJs Typescript,这就是我编写的函数

export async function getStaticProps(){
  let _games:games | any = []
  let url: string | null = `https://api.rawg.io/api/games?key=${key}`

  while(url !== ""){
     _games = [...await fetch(url)
                  .then(res => res.json())
                  .then(
                    data => {
                      if(data["next"] !== null){
                        return url = data["next"].toString()
                      }
                      else return url = null
                    }
                  ).then(res => res.json())]
  }

  return {
    props : {
      _games
    }
  }
}

我试图在下一个属性不为空时获取数据,并将其存储在 _games 变量中,但它不起作用,我在第二个.then(res => res.json()) 收到错误,说res is not a function但是当我删除它时,它返回undefined 也许这不是正确的做法......无论如何我想知道该怎么做。

谢谢!

【问题讨论】:

    标签: javascript reactjs typescript next.js


    【解决方案1】:

    我认为在这种情况下递归更好

    let totalGames = []
    
    async function getDataFromAPIWithRecursive(url) {
        if (!url) return totalGames
    
        let response = await fetch(url)
        let data = await response.json()
    
        totalGames = totalGames.concat(data.results)
    
        await getDataFromAPIWithRecursive(data["next"])
    }
    
    async function getStaticProps(key) {
        await getDataFromAPIWithRecursive(`https://api.rawg.io/api/games?key=${key}`)
    
        return {
            props: {
                totalGames
            }
        };
    }
    
    getStaticProps("API_KEY")

    【讨论】:

    • 显然,这行得通,但我想这需要太多时间和请求,但我认为没有其他解决方案
    • 是的,很遗憾,您将不得不一直等待请求
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 2021-10-24
    • 2011-10-03
    • 2017-04-26
    • 2014-12-03
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多