使用 NHL APi,尝试制作一个只显示每个玩家信息的 React 应用程序。该代码现在确实有效(返回一般名单信息和一名特定球员的数据),但我想显示球队的所有球员信息。不止一个。我是使用多个 API 的新手,大约有 47 个玩家。我真的必须单独获取每个玩家,进行 47 个 API 调用吗?或者,还有更好的方法?想知道我是否能够获取名册 API 一次,然后以某种方式从那里显示所有单个玩家的信息。任何帮助将不胜感激!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);
3 回答
![?](http://img1.sycdn.imooc.com/54584c5e0001491102200220-100-100.jpg)
慕娘9325324
TA贡献1783条经验 获得超4个赞
Promise.all([
fetch(apiSpezza),
fetch(api),
]).then(([data1, data2]) => {
cosnole.log(data1,data2);
})
我会推荐使用 localhost 调用 API,不要直接传递 API URL。
添加回答
举报
0/150
提交
取消