简体   繁体   English

React.js 获取 API 的多个端点

[英]React.js fetch multiple endpoints of API

I am doing a React.js project.我正在做一个React.js项目。 I am trying to pull data from an API that has multiple endpoints.我正在尝试从具有多个端点的API中提取数据。 I am having issues with creating a function that pulls all the data at once without having to do every endpoint separetly.我在创建 function 时遇到问题,它可以一次提取所有数据,而不必分别处理每个端点。 The console.log gives an empty array and nothing gets display. console.log给出了一个空数组,没有任何显示。 The props 'films' is data from the parent and works fine.道具“电影”是来自父母的数据,工作正常。 It is also from another enpoint of the same API.它也来自同一个 API 的另一个端点。 This is the code:这是代码:

import { useEffect, useState } from "react";

import styles from './MovieDetail.module.css';

const MovieDetail = ({films}) => {
    const [results, setResults] = useState([]);

    const fetchApis = async () => {
        const peopleApiCall = await fetch('https://www.swapi.tech/api/people/');
        const planetsApiCall = await fetch('https://www.swapi.tech/api/planets/');
        const starshipsApiCall = await fetch('https://www.swapi.tech/api/starships/');
        const vehicleApiCall = await fetch('https://www.swapi.tech/api/vehicles/');
        const speciesApiCall = await fetch('https://www.swapi.tech/api/species/');
        const json = await [peopleApiCall, planetsApiCall, starshipsApiCall, vehicleApiCall, speciesApiCall].json();
        setResults(json.results)        
    }

    useEffect(() => {
            fetchApis();
    }, [])

    console.log('results of fetchApis', results)

    return (
        <div className={styles.card}>
            <div className={styles.container}>
                <h1>{films.properties.title}</h1>
                <h2>{results.people.name}</h2>
                <p>{results.planets.name}</p>
            </div>            
        </div>
    );
}
 
export default MovieDetail;

UPDATE更新

I just added the post of Phil to the code and I uploaded to a codesanbox我刚刚将 Phil 的帖子添加到代码中,然后上传到了代码

You want to fetch and then retrieve the JSON stream from each request.您想从每个请求中获取并检索 JSON stream。

Something like this像这样的东西

const urls = {
  people: "https://www.swapi.tech/api/people/",
  planets: "https://www.swapi.tech/api/planets/",
  starships: "https://www.swapi.tech/api/starships/",
  vehicles: "https://www.swapi.tech/api/vehicles/",
  species: "https://www.swapi.tech/api/species/"
}

// ...

const [results, setResults] = useState({});

const fetchApis = async () => {
  try {
    const responses = await Promise.all(Object.entries(urls).map(async ([ key, url ]) => {
      const res = await fetch(url)
      return [ key, (await res.json()).results ]
    }))

     return Object.fromEntries(responses)
  } catch (err) {
    console.error(err)
  }
}

useEffect(() => {
  fetchApis().then(setResults)
}, [])

Each URL will resolve to an array like...每个 URL 将解析为一个数组,如......

[ "people", [{ uid: ... }] ]

Once all these resolve, they will become an object (via Object.fromEntries() ) like一旦所有这些解决,它们将成为 object (通过Object.fromEntries() ),如

{
  people: [{uid: ... }],
  planets: [ ... ],
  // ...
}

Take note that each property is an array so you'd need something like请注意,每个属性都是一个数组,因此您需要类似

<h2>{results.people[0].name}</h2>

or a loop.或循环。

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

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