You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Rawg API获取游戏返回undefined问题求助

问题解决:Rawg API返回数据undefined的问题

核心原因

你定义的FetchGamesResponse接口字段名错误。Rawg API的/games接口返回的游戏数组字段是**results(复数)**,但你写成了result(单数),导致res.data.result找不到对应字段,返回undefined。

修复步骤

  1. 修正TypeScript接口的字段名:
interface FetchGamesResponse {
  count: number;
  results: Game[]; // 将result改为results
}
  1. 在请求回调中使用正确字段名,并更新状态(你之前遗漏了更新games状态的逻辑):
useEffect(() => {
  apiClient
    .get<FetchGamesResponse>("/games")
    .then((res) => {
      console.log(res.data.results);
      setGames(res.data.results); // 更新状态让页面渲染游戏列表
    })
    .catch((error) => {
      setError(error.message);
    });
}, []);

补充排查技巧

可以在then回调中先打印完整的返回数据console.log(res.data),直接核对API返回的字段结构,快速定位这类字段不匹配的问题。

内容的提问来源于stack exchange,提问作者Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:35:28