英文:
Type 'AxiosResponse<IUser, any>' is not an array type
问题
我在使用axios响应时遇到一些小问题。
我有一个从API返回用户配置文件的方法:
static async getProfileById(id: string | undefined){
const jwt = localStorage.getItem("jwt");
const response = await axios.get<IUser>(`http://localhost:4000/api/feed/id?id=${id}`, {
headers: {
authorization: "Bearer " + jwt
}
})
return response;
}
接口IUser:
export interface IUser{
_id: string,
title: string,
body: string,
viewed: number,
likes: number,
comments: number,
author: string,
image: string,
__v: number,
date: string,
isLiked: boolean
}
我创建了一个const来存放用户配置文件:
const [subs, setSubs] = useState<IUser[]>([]);
然后我将配置文件添加到const subs中:
for (let i = 0; i < response.length; i++){
const profileSub = await UserService.getProfileById(response[i]);
console.log(typeof profileSub);
setSubs([...subs, ...profileSub])
}
但是我收到错误消息:'Type 'AxiosResponse<IUser, any>' is not an array type'。
我做错了什么?
谢谢。
英文:
I have a some small problem with typing axios response.
I have method that return user profile from API:
static async getProfileById(id: string | undefined){
const jwt = localStorage.getItem("jwt");
const response = await axios.get<IUser>(`http://localhost:4000/api/feed/id?id=${id}`, {
headers: {
authorization: "Bearer " + jwt
}
})
return response;
}
interface IUser:
export interface IPost{
_id: string,
title: string,
body: string,
viewed: number,
likes: number,
comments: number,
author: string,
image: string,
__v: number,
date: string,
isLiked: boolean
}
I create const that I put user profiles:
const [subs, setSubs] = useState<IUser[]>([]);
And there I adding profiles to const subs:
for (let i =0; i < response.length; i++){
const profileSub = await UserService.getProfileById(response[i]);
console.log(typeof profileSub);
setSubs([...subs, ...profileSub])
}
But I got error : 'Type 'AxiosResponse<IUser, any>' is not an array type'.
What am I doing wrong?
Thx.
答案1
得分: 1
subs
是一个类型为 IUser[]
的数组,而 profileSub
是一个类型为 IUser
的对象。你不能将一个对象展开到一个数组中。如果你想要将 profileSub
添加到 subs
数组中,你可以这样做:
setSubs(prevSubs => [...prevSubs, profileSub])
只需将 profileSub
添加到新的 subs
数组中,无需展开它。
注意:如果你想要从 getProfileById
返回用户配置文件,你必须返回 response.data
。
英文:
subs
is an array of type IUser[]
and profileSub
is an object of type IUser
. You cannot spread an object into an array. If you want to add profileSub
to the subs
array, you would do:
setSubs(prevSubs => [...prevSubs, profileSub])
Simply add the profileSub
into the new subs
array without spreading it.
Note: if you want to return the user profile from getProfileById
, you have to return response.data
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论