import React from "react"; import { useParams } from "react-router-dom"; import { useState, useEffect } from "react"; const SingleUser = () => { const [user, setUser] = useState([]); const { username } = useParams(); useEffect(() => { const getSingleUser = async () => { try { const res = await fetch( `https://api.chess.com/pub/player/${username}/stats` ); const data = await res.json(); const heroesArray = Object.values(data); setUser(heroesArray); console.log(heroesArray[0].last); } catch (error) { console.error(error); } }; getSingleUser(); }, []); return ( <section> <div> <h1>Rapid Chess</h1> <p>Current Rating: {user[0].last.rating}</p> <p>Best Rating: {user[0].best.rating} </p> <div> <p>Wins: {user[0].record.win} </p> <p>Losses: {user[0].record.loss} </p> <p>Draws: {user[0].record.draw} </p> </div> </div> </section> ); }; export default SingleUser;
由于某种原因,我的代码只显示一次,当我刷新页面时,我开始出现错误。我认为这与 useEffect 有关,但我不知道
类型错误:无法读取未定义的属性(读取“最后”)。我收到这些错误。
当您处理来自 api 的数据时,您应该使用 可选链,因为数据可能会也可能不会: