使用 NHL APi,嘗試制作一個(gè)只顯示每個(gè)玩家信息的 React 應(yīng)用程序。該代碼現(xiàn)在確實(shí)有效(返回一般名單信息和一名特定球員的數(shù)據(jù)),但我想顯示球隊(duì)的所有球員信息。不止一個(gè)。我是使用多個(gè) API 的新手,大約有 47 個(gè)玩家。我真的必須單獨(dú)獲取每個(gè)玩家,進(jìn)行 47 個(gè) API 調(diào)用嗎?或者,還有更好的方法?想知道我是否能夠獲取名冊(cè) API 一次,然后以某種方式從那里顯示所有單個(gè)玩家的信息。任何幫助將不勝感激!import React, { Component } from "react";import ReactDOM from "react-dom";import "./styles.css";class App extends Component { state = { loading: true, roster: null, spezza: null }; // Always fetch here async componentDidMount() { // Roster const api = "https://statsapi.web.nhl.com/api/v1/teams/10/roster"; const response = await fetch(api); const data = await response.json(); console.log(data.roster[0]); // Spezza const apiSpezza = "https://statsapi.web.nhl.com/api/v1/people/8469455"; const responseSpezza = await fetch(apiSpezza); const dataSpezza = await responseSpezza.json(); console.log(dataSpezza.people[0]); // When the component mounts, set the new state values based on the API this.setState({ loading: false, roster: data.roster[0], spezza: dataSpezza.people[0] }); } render() { return ( <div className="App"> {/* If loading = true - meaning we can't fetch the API, then display loading. If loading value = false, meaning we fetched it, display the values from the API */} {this.state.loading ? ( <div>loading...</div> ) : ( <> <h1>Roster:</h1> <p>Jersey Number: {this.state.roster.jerseyNumber}</p> <p>Full Name: {this.state.roster.person.fullName}</p> <h1>Spezza:</h1> <p>Jersey Number: {this.state.spezza.primaryNumber}</p> <p>Age: {this.state.spezza.currentAge}</p> <p>Height: {this.state.spezza.height}</p> <p>Weight: {this.state.spezza.weight} lbs</p> <p>Nationalty: {this.state.spezza.nationality}</p> </> )} </div> ); }}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);
React:如何獲取多個(gè) API
HUX布斯
2021-10-29 13:26:35