映射数组并返回API结果

时间:2019-05-25 23:56:33

标签: javascript reactjs

尝试使用简单的代码在数组上进行映射,并针对每个结果在API中搜索该结果,然后吐出从API中检索到的数据。

import React from 'react';

const App = () => {

  let artistData = require('./mass-artists.json')

  artistData.map(
    (theArtist) => {
        fetch(`[url]https://api.scryfall.com/cards/search?q=a:[/url]"${theArtist}"`)
            .then((response) => {
              return response.json();
            })
            .then((myJson) => {
              console.log(JSON.stringify(myJson)); //returns the JSON data, so I know it's working
              console.log(myJson.data[0].name); //returns the first card name
            })
    }
  )

  return(<span>This is here so React doesn't yell at me about no return statement.</span>)
}

export default App;

JSON文件只是魔术师姓名的列表。该地图会映射到艺术家列表,并在API上进行搜索。我想对地图做平常的事,即在前端显示一些东西。但是我无法使任何东西正常工作。我可以将内容记录到控制台,也可以执行任何Javascript功能(例如,设置某些内容的innerHTML),但是我将在何处/如何放置return语句以在span标签中显示结果?即使是“ Hello!”。

一如既往的感谢!

1 个答案:

答案 0 :(得分:2)

如果您需要更多有关状态的帮助,建议您在React中研究新的hooks api或旧的Class组件。以下代码将搜索数据,然后设置状态,以便组件知道要更新。 您也可能不想直接在render中运行该映射,因为每次组件更新时,都会重新运行获取。

import React, { useState, useEffect } from "react";

const App = () => {
  const [artistsInfo, setArtistsInfo] = useState([]);

  useEffect(async () => {
    let artistData = require("./mass-artists.json");

    const promises = artistData.map(theArtist => {
      return fetch(
        `[url]https://api.scryfall.com/cards/search?q=a:[/url]"${theArtist}"`
      )
        .then(response => {
          return response.json();
        })
        .then(myJson => {
          return myJson.data;
        });
    });
    const results = await Promise.all(promises);
    // results is an array of arrays because that is what your data seemed to be
    // you could use lodash flatten if you want to get a single array

    setArtistsInfo(results);
  }, []); // empty array so it only runs once

  // you could have a second useState to add a loader if you want

  return artistsInfo.map(infoArray => {
    return infoArray.map(singleInfo => {
      return <span key={singleInfo.id}>{singleInfo.name}</span>;
    });
  });
};

export default App;