【发布时间】:2020-11-23 18:14:18
【问题描述】:
我正在使用一个返回对象列表的 API,然后我希望将其自动映射到 typescript 接口。
API 数据:https://fakestoreapi.com/products
以前我使用过 PokemonAPI,它返回一个带有对象列表的对象 (https://pokeapi.co/)。这个 API 到接口映射工作得很好,因为我的接口 PokemonData 匹配 api 响应。
当来自“fakestoreapi”的 API 响应返回一个列表时,如何让它自动映射?
export interface Pokemon {
id: number,
title: string,
price: number,
description: string,
category: string,
image: string }
export interface PokemonData {
results: Pokemon[]}
//reducer
case GET_POKEMON:
return {
data: action.payload,
loading: false,
error: ''
}
//action
export const getPokemon = (pokemon: string): ThunkAction<void, RootState, null, PokemonAction> => {
return async dispatch => {
try {
const res = await fetch('https://fakestoreapi.com/products')
if (!res.ok) {
const resData: PokemonError = await res.json()
throw new Error(resData.message)
}
const resData: PokemonData = await res.json()
dispatch({
type: GET_POKEMON,
payload: resData
})
}catch(err){
dispatch({
type: SET_ERROR,
payload: err.message
})
}
}
}
【问题讨论】:
-
可能跑题了,但是在 Typescript 中获取数据时,我更喜欢使用 axios 而不是 fetch。例如get方法。可以输入,非常舒服。类似'axios.get
(url) -
@Jerome 谢谢你的提示!
-
axios.get<Pokemon[]>(url);在这种情况下。
标签: reactjs typescript redux react-redux