亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 React 從 API 端點獲取返回值未定義

使用 React 從 API 端點獲取返回值未定義

莫回無 2022-12-22 14:29:57
我正在嘗試從此 NHL API 獲取數據:https ://statsapi.web.nhl.com/api/v1/people/8477474/當我將調用輸出到我的頁面時,它返回 undefined 并且我無法讓它顯示該值。奇怪的是,對象中的第一個元素正確顯示,但沒有任何嵌套元素。這是我的代碼import React, {Component} from "react"class App extends Component {constructor() {    super()    this.state = {      loading: false,      player: {}    }} componentDidMount() {  this.setState({loading: true})  fetch("https://statsapi.web.nhl.com/api/v1/people/8477474/")    .then(response => response.json())    .then(data => {         this.setState({           loading: false,            player: data         })}) }render() {   const fullname = this.state.loading ? "Loading..." : this.state.player.people[0].fullName;   return (         <div>            {fullname }        </div>     )}}export default App這不應該返回未定義的,因為關鍵值顯然在那里,我相信我的目標是正確的。我嘗試了控制臺日志記錄,但我也未定義。我也嘗試刪除 [0] 并執行 this.state.player.people.fullName 和各種替代方法,但沒有成功。
查看完整描述

3 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

將加載的初始狀態設置為true,并刪除行this.setState({loading: true})。



查看完整回答
反對 回復 2022-12-22
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

有一小段時間loading是假的,數據還player沒有。嘗試以下


const fullname = Object.keys(this.state.player).length ? this.state.player.people[0].fullName:""


return ( 

    <div>

        {this.state.loading ? "Loading....": fullname }

    </div> 

)


查看完整回答
反對 回復 2022-12-22
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您可以將播放器狀態初始化為 null。然后使用這一行。


 const fullname = this.state.player ? this.state.player.people[0].fullName:""


或者,如果您愿意,也可以使用 React Hooks 來做到這一點。


https://codesandbox.io/s/baseball-fetch-api-30ehh?file=/src/App.js


import React, { useState, useEffect } from "react";

import "./styles.css";


export default function App() {

  const [loading, setLoading] = useState(true);

  const [player, setPlayer] = useState();

  useEffect(() => {

    const fetchPeople = async () => {

      await fetch("https://statsapi.web.nhl.com/api/v1/people/8477474/")

        .then((res) => res.json())

        .then((res) => setPlayer(res))

        .then(() => setLoading(false))

        .catch((err) => setLoading(err));

    };

    fetchPeople();

  }, []);


  console.log(player);

  const fullname = player ? player.people[0].fullName : "";

  return <div className="App">{loading ? "Loading...." : fullname}</div>;

}


查看完整回答
反對 回復 2022-12-22
  • 3 回答
  • 0 關注
  • 92 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號