【问题标题】:Trouble mapping API response data to typescript interface无法将 API 响应数据映射到 typescript 接口
【发布时间】: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&lt;Pokemon[]&gt;(url); 在这种情况下。

标签: reactjs typescript redux react-redux


【解决方案1】:

您的resData 不是PokemonData 类型,而是Pokemon[] 类型。

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2019-01-06
    • 2021-04-12
    • 2020-08-08
    • 2021-05-23
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多