React组件中Axios返回undefined问题求助(附iTunes请求代码)
问题分析与解决方案
嘿,我一眼就瞅出问题所在啦——你控制台能看到响应数据,但函数返回undefined,核心原因是你的then回调里只做了打印,没有返回数据!
咱们来看修改后的代码,我把关键部分标出来了:
import axios from 'axios'; module.exports = { getItunesArtists: function(ARTIST_NAME) { var encodedURI = window.encodeURI('https://itunes.apple.com/search?term=' + ARTIST_NAME); return axios.get(encodedURI).then(function(response) { console.log('response.data.items', response.data.items); // 👇 这里是关键!把需要的数据返回给Promise链 return response.data.items; }); }, };
为啥之前会返回undefined?
Axios的get方法返回的是一个Promise对象,当你用then处理响应时,then回调的返回值会成为这个Promise最终resolve的结果。之前你的then里没有return任何内容,JS就会默认返回undefined,所以调用这个函数时拿到的就是undefined啦。
调用示例(顺便加个错误处理更稳妥)
// 调用函数时这样用,就能拿到正确的数据了 yourModule.getItunesArtists('Coldplay') .then(artists => { console.log('获取到的艺术家列表:', artists); // 在这里处理你的业务逻辑 }) .catch(error => { console.error('请求失败啦:', error); });
另外提个小细节:iTunes官方搜索API的返回数据其实是存在response.data.results字段里的,如果你后续发现items是undefined,可以检查下这个字段~不过看你控制台能打印出items,应该是没问题的😉
内容的提问来源于stack exchange,提问作者Antonio Pavicevac-Ortiz
相关产品推荐
相关产品推荐

