gpt4 book ai didi

reactjs - React 和 Typescript,Axios 响应的类型?

转载 作者:行者123 更新时间:2023-12-04 11:04:56 26 4
gpt4 key购买 nike

我试图从返回这个的 API 中呈现一个简单的用户列表:

[{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}]

我不完全理解如何处理带有类型的 Axios 响应。 typescript 错误是
Type '{} | { id: number; firstName: string; }' is not assignable to type 'IntrinsicAttributes & UserListProps & { children?: ReactNode; }'.
Property 'items' is missing in type '{}' but required in type 'UserListProps'.

来自 <UserList /> Users.tsx 中的元素下面的文件。是我的 User界面不对?
import React, {useEffect, useState, Fragment } from 'react';
import UserList from './UserList';
import axios, {AxiosResponse} from 'axios';

interface User {
id: number;
firstName: string;
}

const Users: React.FC = (props) => {
const [users, setUserList] = useState<User>();

useEffect(() => {
// Use [] as second argument in useEffect for not rendering each time
axios.get('http://localhost:8080/admin/users')
.then((response: AxiosResponse) => {
console.log(response.data);
setUserList( response.data );
});
}, []);

return (
<Fragment>
<UserList {...users} />
</Fragment>

);
};
export default Users;

下面是我的 UserList.tsx .
import React, {Fragment } from 'react';

interface UserListProps {
items: {id: number, firstName: string}[];
};

const UserList: React.FC<UserListProps> = (props) => {
return (
<Fragment>
<ul>
{props.items.map(user => (
<li key={user.id}>
<span>{user.firstName}</span>
{/* not call delete function, just point to it
// set this to null in bind() */}
</li>
))}
</ul>
</Fragment>
);
};

export default UserList;

最佳答案

generic get method defined in axios/index.d.ts

get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;

例子

interface User {
id: number;
firstName: string;
}


axios.get<User[]>('http://localhost:8080/admin/users')
.then(response => {
console.log(response.data);
setUserList( response.data );
});

- 编辑

我认为您将列表以错误的方式传递给子组件。

const [users, setUserList] = useState<User[]>([]);
<UserList items={users} />

interface UserListProps {
items: User[];
};

const UserList: React.FC<UserListProps> = ({items}) => {
return (
<Fragment>
<ul>
{items.map(user => (
<li key={user.id}>
<span>{user.firstName}</span>
</li>
))}
</ul>
</Fragment>
);
};

关于reactjs - React 和 Typescript,Axios 响应的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62217642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com