reactjs - 无法将 API 响应数据映射到 typescript 接口(interface)

标签 reactjs typescript redux react-redux

我正在使用一个返回对象列表的 API,然后我想将其自动映射到 typescript 接口(interface)。

API 数据:https://fakestoreapi.com/products

之前我使用过 PokemonAPI,它返回一个包含对象列表的对象 (https://pokeapi.co/)。这个 API 到接口(interface)映射工作得很好,因为我的接口(interface) 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
        })
    }
}

最佳答案

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

关于reactjs - 无法将 API 响应数据映射到 typescript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63233500/

相关文章:

javascript - 从 JS 中的不可变数组中删除元素的最干净方法是什么?

reactjs - Semantic-UI-react 固定侧边栏

javascript - 为什么设置 "No license field": true in your package. json 时 "private"警告消失

javascript - 传递一个空的 Prop (没有 api 值)来 react 组件

javascript - ReactJS - 更改另一个组件呈现的内容的组件

javascript - 有没有办法禁用 Redux 警告 : A non-serializable value was detected in the state

javascript - 从获取异步数据的父组件接收 Prop 时的 setState

javascript - Angular2 服务未将 JSON 传递给 WebAPI

css - 将 Angular Material 选项卡正文内容向左对齐

angular - TypeScript:无法读取 datepipe.transform 中未定义的属性 'transform'