arrays - 如何将映射项附加到新数组中
问题描述
我有一些object
s 是从那些s那里得到map()
的,并将这些对象作为 s (见图)。API
URL
fetch()
URL
return
所以我想将所有这些object
s 放入一个新array
的中,这样我就可以使用array
来创建一个react component
将使用那里的信息的。
谁能帮我弄清楚如何解决这个问题给我一些提示?之前谢谢。
const url = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=5";
const AppProvider = ({ children }) => {
const fetchUrl = async () => {
const resp = await fetch(url);
const respData = await resp.json();
const data = respData.results;
data.map((pokemon) => {
fetchPokemon(pokemon);
});
};
const fetchPokemon = (pokemon) => {
let url = pokemon.url;
fetch(url)
.then((resp) => resp.json())
.then((pokemonData) => {
finalData(pokemonData);
});
};
const finalData = (pokemonData) => {
console.log(pokemonData, "data");
};
};
解决方案
您可以通过在 map 函数中返回数据来创建所需的对象数组,然后将其推送到数组中。
const url = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=5";
const AppProvider = ({ children }) => {
const fetchUrl = async () => {
const resp = await fetch(url);
const respData = await resp.json();
const data = respData.results;
const newArray = [];
data.map((pokemon) => {
newArray.push(fetchPokemon(pokemon));
});
};
const fetchPokemon = async (pokemon) => {
let url = pokemon.url;
let data = {}
return fetch(url)
.then((resp) => resp.json())
.then((pokemonData) => {
return pokemonData;
});
};
};
推荐阅读
- python - 在使用制表或文本表库时,python IDLE 中的输出失真
- apache - 我无法在我的树莓派网络服务器上运行我的应用程序
- c - c struct,2 个变量赋值类型
- python - 如何在 Python 中使用正则表达式提取名称列表?
- sql - 雪花窗函数 last_value 和 max
- c# - 以编程方式将 packageSource 添加到 Nuget.Config 中的 packageSources
- angular - 指令从 contexmenu 更改 ngmodel 输入值
- c# - 基于语法的自定义字符串分隔
- html - 具有相同输入字段的多个表单的一个 ajax
- string - 遍历文件中的行并从 vec 中查找子字符串!生锈