programing

React 및 TypeScript - Axios 응답 유형

nicescript 2023. 3. 8. 23:48
반응형

React 및 TypeScript - Axios 응답 유형

API에서 간단한 사용자 목록을 표시하려고 합니다.이 목록은 다음과 같습니다.

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

Axios의 회신을 타입으로 처리하는 방법을 잘 모르겠습니다.TypeScript 오류는 다음과 같습니다.

'{} | { id: number; firstName: string; }'을(를) 'IntrinsicAttributes & UserListProps & { children' 유형에 할당할 수 없습니다.React Node; }''

유형 '{}'에는 속성 'items'가 없지만 유형 '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;

axios/index.d.ts에 정의되어 있는 범용 메서드가 있습니다.

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

호출할 때 형식 인수를 제공해야 합니다.axios.getAxios가 값의 유형을 추론하지 않도록 하려면response다른 것과 마찬가지로.

잘못된 타입 인수를 전달하고 있는데useState사용자 배열을 만듭니다.

올바른 방법

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

// Initialized as an empty array
const [users, setUserList] = useState<User[]>([]); // 'users' will be an array of users

예를들면,

import React, {useEffect, useState, Fragment } from 'react';
import UserList from './UserList';
import axios from 'axios';

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

// You can export the type TUserList to use as -
// props type in your `UserList` component
export type TUserList = User[]

const Users: React.FC = (props) => {
   // You can also use User[] as a type argument
    const [users, setUserList] = useState<TUserList>();

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

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

    );
};
export default Users;

유형을 내보내도록 선택한 경우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>
                    { /* Do not call the delete function. Just point
                         to it. Set this to null in bind(). */}
                </li>
            ))}
            </ul>
        </Fragment>
    );
};

export default UserList;

언급URL : https://stackoverflow.com/questions/62217642/react-and-typescript-which-types-for-an-axios-response

반응형