簡體   English   中英

獲取數據前異步獲取 API 時返回 Null

[英]Returning Null When Fetching API Asynchronously Before Data Fetches

我的嘗試

我試圖多次獲取 API 並將數據放入表中。 因此,我多次調用 API。 我試圖做到這一點,如果某一年的數據在那里,它會填滿一張表格,但如果沒有,則不顯示任何內容。 如果所有年份的數據都存在,它會很好地加載和填充表格,但如果不是,它就會中斷。 這就是我正在使用的。

主文件

 <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 未定義。 我希望它什么都不返回。

我試過的

我試過在 return 語句中放置一個 if 語句,a la:

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 和 then/catch。

嘗試將您的函數更改為僅使用 then/catch,因此只需將其放入帶有空 dep 數組的 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 並檢查那里發生了什么。

檢查你得到的道具,也許有什么問題? 如果上述方法不起作用,請隨時提供更多信息。

也盡量不要在聲明之前調用函數:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM