【发布时间】:2020-08-25 10:35:12
【问题描述】:
我正在使用 NHL API 并为我的应用检索曲棍球统计数据。 API 有多个端点,我使用它们来访问玩家统计信息。
Roster endpoint
https://statsapi.web.nhl.com/api/v1/teams/3/roster
检索此数据后,我可以访问一个名为 person 的对象,其中包含该个人玩家的 API 端点的 ID 号,其中包含谱系信息(即他们来自的国家、身高/体重等)。然后我可以发送一个类似这样的 API 请求来检索该单个玩家的更多数据,在这种情况下,8476191 是 ID 号。
Pedigree Info endpoint:
https://statsapi.web.nhl.com/api/v1/people/8476191
我还可以将 ID 号 8476191 传递到包含同一玩家的统计数据的统计端点。
Stats endpoint:
https://statsapi.web.nhl.com/api/v1/people/8476191/stats?stats=statsSingleSeason&season=20182019
我想做的是向Roster endpoint 发送请求,获取名单上每个球员的ID 号,然后使用ID 号对Pedigree info endpoint 和stats endpoint 进行后续API 调用.
如何向名册端点发出Axios get 请求,然后在调用中再嵌套两个 get 请求,以便从第一次调用中访问 ID 号?这是我尝试过的:
// State for retrieving player ID numbers from roster endpoint
const [playerIDNumbers, setPlayerIDNumbers] = useState([]);
useEffect(() => {
// Get the roster data, set playerIdNumbers to an array containing all the ID numbers
axios.get(`https://statsapi.web.nhl.com/api/v1/teams/${teams[teamName].id}/roster`)
.then(res => {
setPlayerIDNumbers(Object.values(res.data.roster).map((x) => {
return x.person.id;
}));
// res now contains all the ID numbers
console.log(res);
})
// After grabbing all the ID numbers for each player on the roster, I want to map through each ID
// in the array and send a request for each player's pedigree data
.then(res => {
// Later in my code I created an array to contain the IDs called playerIDArr
playerIDArr.map((playerID) => {
axios.get(`https://statsapi.web.nhl.com/api/v1/people/${playerID}/`)
})
console.log('Player ID call returned : ' + res);
})
// After this is done I want to make a third request using the ID numbers to grab the stats /////from the stats endpoint
/* Stats Axios request would go here */
.catch(err => {
console.log('Error : ' + err);
})
}, [])
【问题讨论】:
-
不确定为什么要在 state 中设置玩家 ID 号码,您可以返回号码并使用下一个
.then中的 ID 执行 Promise.all。您目前尝试使用 playerIDArr 的stale closure
标签: reactjs promise axios react-hooks use-effect