Reactjs React和Typescript,Axios响应的类型是什么?

Reactjs React和Typescript,Axios响应的类型是什么?,reactjs,typescript,axios,Reactjs,Typescript,Axios,我试图从API中提供一个简单的用户列表,该列表返回以下内容: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] 我不完全理解如何使用类型处理Axios响应。类型脚本错误为 Type '{} | { id: number; firstName: string; }' is not assignable to type 'IntrinsicAttributes & UserListProps &

我试图从API中提供一个简单的用户列表,该列表返回以下内容:

[{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}]
我不完全理解如何使用类型处理Axios响应。类型脚本错误为

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
文件中的
元素。我的
用户
界面是否错误

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;

get(url:string,config?:AxiosRequestConfig):Promise;
范例

用户界面{
id:编号;
名字:字符串;
}
axios.get()http://localhost:8080/admin/users')
。然后(响应=>{
console.log(response.data);
setUserList(response.data);
});
--编辑

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

const[users,setUserList]=useState([]);
constuserlist:React.FC=({items})=>{
返回(
    {items.map(用户=>(
  • {user.firstName}
  • ))}
); };
调用
axios时,需要提供类型参数。如果不希望axios推断值
响应的类型,请获取

当您
useState
创建用户数组时,传递的类型参数不正确

正道

用户界面{
id:编号;
名字:字符串;
}
//初始化为空数组
const[users,setUserList]=useState([]);//用户将是一组用户
比如说,

import React, {Fragment } from 'react';
import { TUserList } from './Users';

interface UserListProps {
    items: TUserList // don't have to redeclare the object again
};

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;
import React,{useffect,useState,Fragment}来自'React';
从“/UserList”导入用户列表;
从“axios”导入axios;
界面用户{
id:编号;
名字:字符串;
}
//您可以导出类型TUserList以用作-
//在“用户列表”组件中键入道具
导出类型TUserList=User[]
常量用户:React.FC=(道具)=>{
//您还可以使用User[]作为类型参数
const[users,setUserList]=useState();
useffect(()=>{
//使用[]作为useEffect中的第二个参数,以避免每次渲染
axios.get()http://localhost:8080/admin/users')
。然后((响应)=>{
console.log(response.data);
setUserList(response.data);
});
}, []);
返回(
);
};
导出默认用户;
如果选择导出类型
type TUserList=User[]
,则可以在
UserList
组件中将其用作道具类型。比如说,

import React, {Fragment } from 'react';
import { TUserList } from './Users';

interface UserListProps {
    items: TUserList // don't have to redeclare the object again
};

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;
import React,{Fragment}来自'React';
从“/Users”导入{TUserList};
接口UserListProps{
items:TUserList//不必再次声明对象
};
const UserList:React.FC=(道具)=>{
返回(
    {props.items.map(用户=>(
  • {user.firstName} {/*不要调用delete函数,只需指向它即可 //在bind()*/}中将此设置为null
  • ))}
); }; 导出默认用户列表;
谢谢,所以我应该使用
axios.get
而不是
useState()
?如果我尝试这样做,Typescript会抱怨
useState()
未定义。更新答案。我以为一开始你们只是得到一个对象,但实际上这是一个数组。只需将
[]
放在几个地方,我认为现在唯一缺少的部分是如何初始化
useState()
。我发现:
类型为“User[]”的参数不能分配给类型为“SetStateAction”的参数。键入“User[]”不提供与签名匹配的内容(prevState:undefined):undefined)。ts(2345)
您必须使用空数组初始化
useState([])
。否则,您必须扩展type
useState()
添加检查子组件中是否未定义变量,并对此采取措施导出
TUserList
类型非常好,非常感谢您提供了一个非常好的答案:)我很高兴它有帮助。
import React, {Fragment } from 'react';
import { TUserList } from './Users';

interface UserListProps {
    items: TUserList // don't have to redeclare the object again
};

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;