首页 > 解决方案 > 如何将映射项附加到新数组中

问题描述

我有一些objects 是从那些s那里得到map()的,并将这些对象作为 s (见图)。API URLfetch()URLreturn

所以我想将所有这些objects 放入一个新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");
  };
};

标签: arraysreactjsobject

解决方案


您可以通过在 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;
      });
  };
};


推荐阅读