首頁  >  問答  >  主體

由於某種原因,我的程式碼只顯示一次,當我刷新頁面時,我開始出現錯誤

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 有關,但我不知道

類型錯誤:無法讀取未定義的屬性(讀取「最後」)。我收到這些錯誤。

P粉986028039P粉986028039267 天前298

全部回覆(1)我來回復

  • P粉447495069

    P粉4474950692024-02-18 15:16:59

    當您處理來自 api 的資料時,您應該使用 可選鏈,因為資料可能會也可能不會:

    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 (
        

    Rapid Chess

    Current Rating: {user?.[0]?.last?.rating}

    Best Rating: {user?.[0]?.best?.rating}

    Wins: {user?.[0]?.record?.win}

    Losses: {user?.[0]?.record?.loss}

    Draws: {user?.[0]?.record?.draw}

    ); }; export default SingleUser;

    回覆
    0
  • 取消回覆