React Typescript Axios Response 中缺少类型

Type missinng in React Typescript Axios Response

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

下面是我的代码:

助手接口 API Class

import { AxiosResponse } from 'axios'

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

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

我的平台Class

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 的 属性。如何实现打字稿知道数据是 PlatformResponse 的类型。请帮助完成它。

你从 react-query 得到一个 data 属性,其中包含来自你的 queryFn returns.

的未包装的承诺

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

您的实际 datadata 属性 内,因此您需要:

data.data.platform

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

如果您不需要在 queryCache 中像 headers 那样存储请求 meta-data,最好将其解包在 queryFn:

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

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