为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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 关注
  • 47 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信