简体   繁体   English

有没有办法在另一个 api 呼叫的 map 内进行 api 呼叫?

[英]Is there a way to make an api call within a map of another api call?

I know the title is quite confusing, I wasn't sure how to word it better.我知道标题很混乱,我不确定如何更好地表达它。 What I am trying to do is to fetch some items, map through those items to display them, but the problem is that one of those items has a value of what needs to be another api call to access it.我想要做的是通过这些项目获取一些项目 map 以显示它们,但问题是其中一个项目的值需要另一个 api 调用才能访问它。

This is what I'm trying to do:这就是我想要做的:

First of all I am storing an empty state, which later on becomes the data of the fetched items:首先,我存储一个空的 state,它后来成为获取项目的数据:

const [data, setData] = useState([]);

I'm using axios to fetch and store the data:我正在使用 axios 来获取和存储数据:

const fetchItems = () => {
  axios("https://swapi.dev/api/people")
    .then((response) => {
      console.log(response.data.results);

      const newData = response.data.results.map((item) => ({
        name: item.name,

        homeworld: () => {
          axios.get(item.homeworld).then((response) => {
            response.data.results;
          });
        },
      }));
      setData(newData);
    })

    .catch((error) => {
      console.log("error", error);
    });
};

It works with the name because it's a simple value.它与名称一起使用,因为它是一个简单的值。 However, the homeworld includes a link that needs to be called once again in order to access it, instead of being a simple value like the name in this case.但是,homeworld 包含一个需要再次调用才能访问它的链接,而不是像本例中的名称那样的简单值。 How can I call it and access what values are held within that link, and display them instead of just displaying the url?我如何调用它并访问该链接中包含的值,并显示它们而不是仅显示 url?

I hope this can help you:我希望这可以帮助你:

const [data,setData] = useState([])
const fetchItems = () => {
  axios("https://swapi.dev/api/people")
    .then(response => {
      console.log(response.data.results);

      const { results } = response.data;

      for (const item of results) {
         axios.get(item.homeworld).then(({data}) => {
          setData([...data,{ name: item.name, homeworld: data.results }]);
        });
      }
    })
    .catch(error => {
      console.log("error", error);
    });
};

or with fetch :或者使用fetch

const [data,setData] = useState([])
fetch("https://swapi.dev/api/people").then(re=>re.json())
    .then(response => {
      const newData = []
      const { results } = response;
      const newData = [];
      for (const item of results) {
         fetch(item.homeworld).then(re => re.json()).then((data) => {
             newData.push({ name: item.name, homeworld: data });
         });
      }
      console.log(newData)
      setData(newData)
    })
    .catch(error => {
      console.log("error", error);
    });

Use Promise.all()使用Promise.all()

You can use Promise.all() method to get all the information you need by creating an array of promises by mapping the response.results array with an async function .您可以使用 Promise.all() 方法通过使用异步 function映射response.results数组创建承诺数组来获取所需的所有信息。

This is the code example这是代码示例

const fetchItems = async () => {
  const req = await axios.get("https://swapi.dev/api/people");
  const response = await req.data;

  const allDataPromises = response.results.map(async (item) => {
    const itemReq = await axios.get(item.homeworld);
    const itemResponse = await itemReq.data;
    return {
      name: item.name,
      homeworld: itemResponse,
    };
  });

  const allData = await Promise.all(allDataPromises);
};

For further information about Promise.all() 有关 Promise.all() 的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM