Javascript 使用React从API端点获取返回未定义的值

Javascript 使用React从API端点获取返回未定义的值,javascript,reactjs,api,fetch,Javascript,Reactjs,Api,Fetch,我正在尝试从此NHL API获取数据: 当我将调用输出到我的页面时,它返回undefined,我无法让它显示值。奇怪的是,对象中的第一个元素显示正确,但没有任何嵌套元素 这是我的密码 import React, {Component} from "react" class App extends Component { constructor() { super() this.state = { loading: false, pla

我正在尝试从此NHL API获取数据:

当我将调用输出到我的页面时,它返回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
import React,{Component}来自“React”
类应用程序扩展组件{
构造函数(){
超级()
此.state={
加载:false,
玩家:{}
}
} 
componentDidMount(){
this.setState({loading:true})
取回(“https://statsapi.web.nhl.com/api/v1/people/8477474/")
.then(response=>response.json())
。然后(数据=>{
这是我的国家({
加载:false,
玩家:数据
})
}) 
}
render(){
const fullname=this.state.loading?“正在加载…”:this.state.player.people[0]。fullname;
报税表(
{fullname}
)
}
}
导出默认应用程序
这不应该返回undefined,因为键值显然在那里,我相信我的目标是正确的

我尝试了控制台日志记录,但也没有定义。
我也尝试过删除[0]并执行此操作。state.player.people.fullName和各种选项,但没有成功。

将加载的初始状态设置为
true
,并删除行
this.setState({loading:true})

有一小段时间,
加载
是错误的,并且数据还不在
播放器中。试试下面的方法

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

return ( 
    <div>
        {this.state.loading ? "Loading....": fullname }
    </div> 
)
const fullname=Object.keys(this.state.player).length?this.state.player.people[0]。全名:“
报税表(
{this.state.loading?“loading…”:全名}
)

您可以将玩家状态设置为空。然后用这条线

const fullname=this.state.player?this.state.player.people[0]。全名:“

或者,如果您愿意,也可以使用React钩子

import React,{useState,useffect}来自“React”;
导入“/styles.css”;
导出默认函数App(){
const[loading,setLoading]=useState(true);
const[player,setPlayer]=useState();
useffect(()=>{
const fetchPeople=async()=>{
等待取回(“https://statsapi.web.nhl.com/api/v1/people/8477474/")
.然后((res)=>res.json())
.然后((res)=>setPlayer(res))
.然后(()=>setLoading(false))
.catch((err)=>设置加载(err));
};
fetchPeople();
}, []);
控制台日志(播放器);
const fullname=player?player.people[0]。全名:“”;
返回{正在加载?“正在加载…”:fullname};
}

我认为此解决方案更为理想,因为可以减少渲染次数。现在可能还可以,但当你的应用程序变得更大时,您将希望减少不必要的渲染。这是唯一合乎逻辑的解决方案@JakeMartinez。鉴于您的应用程序在没有来自终结点的数据的情况下中断,因此在初始状态下将
加载
设置为
也没有意义。如果此解决方案更好。我认为你的答案是正确的。再次感谢,没问题。很高兴为您提供帮助。您是否介意帮助我循环浏览100名玩家,并在页面上显示他们的姓名?我试过几种方法,但我正在寻找最有效的方法。当然。共享一个代码沙盒之类的东西。你可能只需要在玩家之间绘制地图。类似于players.map((player)=>player.name)这是沙箱:
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>;
}