【问题标题】:Type missinng in React Typescript Axios ResponseReact Typescript Axios 响应中缺少类型
【发布时间】:2022-01-28 15:53:45
【问题描述】:

我正在尝试使用 Axios 和 Typescript 在 React 应用程序中编写 API 服务。

下面是我的代码:

Helper API 类的接口

import { AxiosResponse } from 'axios'

export interface PlatformResponse {
    platform: {
        id: string
        image: string
        name: string
    }[]
}

export interface Platform {
    getPlatformResponse: () => Promise<AxiosResponse<PlatformResponse>>
}

我的平台类

import { AxiosResponse } from 'axios'

class Platforms implements Platform {
    async getPlatformResponse(): Promise<AxiosResponse<PlatformResponse>> {
        const path = 'http://localhost:8080/api/platforms'
        const method = 'get'
        const result = await httpRequest({ path, method })
        return result
    }
}

const PlatformsAPI = new Platforms()
export default PlatformsAPI 

我正在使用 react-query 库来获取数据,以及下面的代码

const useGetPlatforms = () => {
    console.log('sdfd')
    return useQuery('platform', PlatformsAPI.getPlatformResponse)
}

export default useGetPlatforms

我的组件的代码如下

import { useGetVehicleBrands } from '../../../hooks/RQHooks'

function VehicleBrands() {
    const { data, isLoading } = useGetVehicleBrands()
    console.log('data', data.platform)

    return (
        <>
            <div>
                {data.platform.map((item) =><h1>{item}</h1>)}
            </div>
        </>
    )
}

export default PlatformComponent

我在上面的代码中遇到的错误是我无法从数据中访问平台属性。打字稿抛出错误,说找不到平台属性。仅显示来自 AxiosResponse 的属性。如何实现 typescript 知道 data 是 PlatformResponse 的类型。请帮助完成它。

【问题讨论】:

  • 在您的问题中添加错误日志作为代码块

标签: reactjs typescript axios react-typescript react-query


【解决方案1】:

您从 react-query 获得一个 data 属性,其中包含来自您的 queryFn 返回的任何未包装的承诺。

AxiosResponse 包含您在屏幕截图中看到的内容 - dataheadersstatusText 等。

您的实际 data 位于 data 属性内,因此您需要:

data.data.platform

第一个 data 来自 react-query,第二个来自 axios。

如果您不需要在 queryCache 中存储请求元数据(如标头),最好在 queryFn 中解包:

useQuery(
  'platform',
   () => PlatformsAPI.getPlatformResponse().then(response => response.data))
)

如果需要,您也可以在 PlatformsAPI 中执行此操作。

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2015-12-02
    • 2021-02-21
    • 1970-01-01
    • 2017-06-08
    • 2020-01-19
    • 1970-01-01
    • 2020-05-09
    • 2019-02-07
    相关资源
    最近更新 更多