【发布时间】: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