3 回答
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>
)
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>;
}
添加回答
举报