我正在尝试通过 API 呈现一个简单的用户列表,该列表返回以下内容:
[{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}]
我不完全了解如何处理带有类型的 Axios 响应。TypeScript 错误是
类型’{} | { id: number; firstName: string; }’ 不能分配给类型’IntrinsicAttributes & UserListProps & { children?: ReactNode; }’。 类型“{}”中缺少属性“items”,但类型“UserListProps”中需要该属性。
类型’{} | { id: number; firstName: string; }’ 不能分配给类型’IntrinsicAttributes & UserListProps & { children?: ReactNode; }’。
类型“{}”中缺少属性“items”,但类型“UserListProps”中需要该属性。
来自下面文件<UserList />中的元素Users.tsx。我的User界面错了吗?
<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。
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;
get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): 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> ); };