使用Axios按ID请求数据返回数组而非对象,读取属性报undefined
问题解决方法
你的问题核心是服务器返回的数据结构与你声明的TypeScript类型不匹配:你预期返回单个IBlog对象,但实际服务器返回的是包含目标对象的数组,直接访问数组的属性自然会得到undefined。
修正步骤:
调整响应类型声明
将axiosInstance.get<IBlog>改为axiosInstance.get<IBlog[]>,明确告诉TypeScript响应数据是博客对象数组:export const getBlog = async (id: string) => { // 修正类型为IBlog数组 const { data } = await axiosInstance.get<IBlog[]>(`/blogs/${id}`); console.log(data); // 取数组第一个元素(从截图看数组仅包含目标对象) return data[0]; };添加边界处理(可选但推荐)
如果服务器有可能返回空数组,建议添加判断避免报错:export const getBlog = async (id: string) => { const { data } = await axiosInstance.get<IBlog[]>(`/blogs/${id}`); console.log(data); // 检查数组是否有元素,有则返回第一个,否则抛出错误或返回空值 if (data.length === 0) { throw new Error(`未找到ID为${id}的博客`); // 或者 return null; } return data[0]; };验证返回值
调用该函数后,即可正常访问博客对象的属性:const blog = await getBlog('123'); console.log(blog.title); // 不再返回undefined
内容的提问来源于stack exchange,提问作者Mihai Herinean
相关产品推荐
相关产品推荐

