reactjs - 无法将 API 响应数据映射到 typescript 接口
问题描述
我正在使用一个返回对象列表的 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
})
}
}
}
解决方案
你resData
的不是 typePokemonData
而是 type Pokemon[]
。
推荐阅读
- javascript - 我从 for 循环中获得的数组总和返回 NaN (Javascript)
- javascript - ReactJS — 创建 Refs 并访问 DOM 元素以使用 fullpage.js
- nestjs - 如果存在 uid 选项,则返回特定用户,否则返回整个用户列表
- glsl - OpenGL:将 RGBA 转换为浮点数
- swift - 从 Firestore 快照更新 ChatModel 字典中的现有项目
- python - 如何使用 python boto3 将文件和文件夹从一个 S3 存储桶复制到另一个 S3
- c# - 如何在 Xamarin.forms 的 ListView 中显示 ListView
- reactjs - 从 API 获取日志但不渲染
- docker - 在 docker-compose 中创建卷
- java - 如何计算与 Linux、Mac 和 Windows 兼容的 Java (JavaFX) 中用户编写的设置文件的文件路径?