我试图从一个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'.

来自下面Users.tsx文件中的<UserList />元素.我的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 = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;

Example

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>
    );
};

Typescript相关问答推荐

在角形加载组件之前无法获取最新令牌

为什么ESLint抱怨通用对象类型?

如何在方法中定义TypeScript返回类型,以根据参数化类型推断变量的存在?

如何将联合文字类型限制为文字类型之一

为什么TypeScript假设文档对象始终可用?

如何提取密钥及其对应的属性类型,以供在新类型中使用?

Angular 错误NG0303在Angular 项目中使用app.Component.html中的NGFor

React重定向参数

如何在typescript中设置对象分配时的键类型和值类型

对于合并对象中的可选属性(例如选项),类型推断可能是错误的

TypeScrip 5.3和5.4-对`Readonly<;[...number[],字符串]>;`的测试版处理:有什么变化?

为什么不能使用$EVENT接收字符串数组?

如何使用Geojson模块和@Types/Geojson类型解析TypeScrip中的GeoJSON?

具有自引用属性的接口

如何从MAT-FORM-FIELD-MAT-SELECT中移除焦点?

React router 6(数据路由)使用数据重定向

棱角分明-什么是...接口类型<;T>;扩展函数{new(...args:any[]):t;}...卑鄙?

完全在类型系统中构建的东西意味着什么?

映射类型不是数组类型

如何为对象数组中的每个条目推断不同的泛型