React中componentDidMount调用Spotify.getUserPlaylists为何返回undefined
根因分析
- Promise链式调用断裂:在
getCurrentUserId().then()的回调内发起的fetch请求,没有显式return对应的Promise链,导致外层.then()不会等待fetch接口返回,直接执行完毕返回undefined,此时await拿到的就是这个空值。 - async函数未返回有效值:整个
getUserPlaylists方法没有显式把最终的播放列表数组返回,按照async函数的运行规则,没有指定返回值时,函数返回的Promise的resolve值为默认的undefined,因此componentDidMount中获取到的结果始终是空值。 - 隐藏问题:原代码中fetch请求的URL开头多了一个空格,会导致请求路径拼接异常,需要删除。
修正方案
将getUserPlaylists方法的Promise链路打通,同步使用async/await语法简化逻辑,确保最终结果被显式return:
async getUserPlaylists() { const userId = await Spotify.getCurrentUserId(); const accessToken = Spotify.getAccessToken(); const headers = { Authorization: `Bearer ${accessToken}` }; // 删除URL开头的多余空格 const response = await fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, { headers: headers }); const resJson = await response.json(); if (!resJson.items) { return []; } console.log(resJson.items); return resJson.items; }
效果验证
修正后,getUserPlaylists会把return的播放列表数组包装成Promise的resolve值,componentDidMount中通过await拿到的结果,和方法内部打印的数组完全一致。
内容的提问来源于stack exchange,提问作者DeveloperLV
相关产品推荐
相关产品推荐

