使用Rawg API获取游戏返回undefined问题求助
问题解决:Rawg API返回数据undefined的问题
核心原因
你定义的FetchGamesResponse接口字段名错误。Rawg API的/games接口返回的游戏数组字段是**results(复数)**,但你写成了result(单数),导致res.data.result找不到对应字段,返回undefined。
修复步骤
- 修正TypeScript接口的字段名:
interface FetchGamesResponse { count: number; results: Game[]; // 将result改为results }
- 在请求回调中使用正确字段名,并更新状态(你之前遗漏了更新
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
相关产品推荐
相关产品推荐

