【问题标题】:Fetching from API endpoint with React returns value undefined使用 React 从 API 端点获取返回值 undefined
【发布时间】:2020-11-27 08:21:32
【问题描述】:

我正在尝试从此 NHL API 获取数据:https://statsapi.web.nhl.com/api/v1/people/8477474/

当我将调用输出到我的页面时,它返回未定义,我无法让它显示值。奇怪的是,对象中的第一个元素正确显示,但没有任何嵌套元素。

这是我的代码

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 和各种替代方案,但没有运气。

【问题讨论】:

    标签: javascript reactjs api fetch


    【解决方案1】:

    设置加载的初始状态为true,去掉this.setState({loading: true})这一行。

    【讨论】:

    • 我相信这个解决方案更优化,因为你减少了渲染的次数。现在可能没问题,但是当你的应用变得更大时,你会想要减少不必要的渲染。
    • 这是唯一合乎逻辑的解决方案?
    • @JakeMartinez 在初始状态下将loading 设置为false 也是没有意义的,因为您的应用程序在没有来自端点的数据的情况下中断。
    • true 这个解决方案更好。我将您的答案设置为正确答案。再次感谢。
    • 没有问题。很高兴能帮上忙
    【解决方案2】:

    有一小段时间loading 为假且数据尚未在player 中。试试下面的

    const fullname = Object.keys(this.state.player).length ? this.state.player.people[0].fullName:""
    
    return ( 
        <div>
            {this.state.loading ? "Loading....": fullname }
        </div> 
    )
    

    【讨论】:

      【解决方案3】:

      您可以将播放器状态初始化为 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>;
      }
      
      

      【讨论】:

      • 另外你介意帮助我循环播放 100 名玩家并在页面上显示他们的名字吗?我尝试了几种方法,但我正在寻找最有效的方法。
      • 当然。分享一个代码沙箱什么的。您可能只需要通过玩家进行映射。类似于 player.map((player) => player.name)
      猜你喜欢
      • 2019-08-04
      • 2014-09-10
      • 1970-01-01
      • 2018-09-03
      • 2023-03-07
      • 2016-09-13
      • 2021-04-10
      • 2021-09-03
      相关资源
      最近更新 更多