在获取数据之前异步获取API时返回Null



我的尝试

我试图多次获取API并将数据放入表中。因此,我要多次调用API。我试着这样做,如果某一年的数据在那里,它填充一个表格,但如果没有,什么都不显示。如果所有年份的数据都在那里,它就会加载并填充表,但如果不是,它就会中断。这是我正在处理的。

MAIN.JS

<table>
<thead>
<tr>
<th>Season</th>
<th>GP</th>
</tr>
</thead>
<tbody>
<SkaterTableStats season={currentSeason} id={props.id} />
<SkaterTableStats season={prevSeason} id={props.id} />
</tbody>
</table>

SKATERTABLESTATS.JS

import React, {useState, useEffect} from 'react'
function SkaterTableStats(props) {
const [playerStat, setPlayerStat] = useState(null);
useEffect(() => {
getInfoData();
async function getInfoData() {
const statx = await fetch(`https://statsapi.web.nhl.com/api/v1/people/${props.id}/stats?stats=statsSingleSeason&season=${props.season}`)
.then(response => response.json());
setPlayerStat(statx);
}
}, []);

if (playerStat) { 
return (
<tr>
<td>{playerStat.stats[0].splits[0].season}</td>
<td>{playerStat.stats[0].splits[0].stat.games}</td> 
</tr>    
)} else {
return (null)
}
}
export default SkaterTableStats

不幸的是,当加载API时,它总是显示一些,这通常是运动的文案等,但没有统计数据。

通常发生的事情

调用数据-如果球员已经打了x年,数据填充没有问题

-如果玩家没有玩x年,数据填充直到它到达那一年,然后中断,说playerStat。statsEtc未定义。我想让它返回什么。

What I've try

我尝试在返回语句中放入if语句,例如:

if (playerStat) {
return (
etc
) 
}

,但是因为它是异步加载数据加载之前,和休息。相同:

if (!playerStat.stats[0].splits[0].stat.timeOnIce > 0) {
return etc

if (playerStat == undefined) {
return etc

但是都没有成功。
我本来想把返回的数据放到一个表中,但表的格式很奇怪,React需要任何返回在一个封闭的div中,在这种情况下是。但是,如果我添加另一个div或类似的东西,它将打破表格并将所有信息放在一列中。

感谢任何帮助,我很乐意澄清任何需要澄清的事情。谢谢。

最好不要同时使用async/await和/catch。

试着改变你的函数,只使用then/catch,所以简单地把它放在useEffect中,并使用空的深度数组

fetch(`https://statsapi.web.nhl.com/api/v1/people/${props.id}/statsstats=statsSingleSeason&season=${props.season}`)
.then(response => response.json())
.then(response => setPlayerStat(response);

也许可以在。then()中放入一些控制台日志,试着找出你得到的答案是什么,试着重新构建它,只使用async/await,并检查那里发生了什么。

检查你得到的道具,也许有什么问题?如果上述方法不奏效,请随时提供进一步的信息。

也尽量不要在函数声明之前调用它们:)