【发布时间】: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