结合打字稿和获取的正确方法

问题描述 投票:0回答:1

我正在学习 React 和 Typescript。 我有一个带有 ApiPlatform 的后端服务器。 我想在前端使用 fetch 来创建或更新具有其能力的 Pokemon。

我下面的代码可以工作,但它不是“干净”,我使用 let data... 将能力转换为 iri 引用数组,但我不想在创建/更新时重复此代码。

static updatePokemon(pokemon: Pokémon): Promise<Pokemon> { 
let data = { 
  id: pokemon.id, 
  name: pokemon.name, 
  abilities: pokemon.abilities.map(a => '/api/abilities/' + a.id) 
};
return fetch(ENTRY_POINT + '/api/pokemons/' + pokemon.id, {
  method: 'PUT',
  body: JSON.stringify(data),
  headers: { 'Content-Type': 'application/json' }
})
  .then(response => response.json())
  .catch(error => this.handleError(error));
}`

也许 Object.keys(object).reduce.. 在其他文件中?

提前致谢

reactjs typescript api-platform.com
1个回答
0
投票

我想我会把它封装在 pokemon 类中。它可能会暴露

marshall(): <IPokemonDto>

“marshall”在 CakePHP 文档中得到了很好的定义:“Marshall”[...] 包含将数组数据转换为实体的逻辑。将请求数据转换为实体时很有用。

IPokemonDTO 是普通的 javascript 对象,但现在它实现了一个接口。

interface IPokemonDTo {
    id: number;
    name: string;
    abilities: string[];
}

编辑:格式化

© www.soinside.com 2019 - 2024. All rights reserved.