由於某種原因,我的程式碼只顯示一次,當我刷新頁面時,我開始出現錯誤
P粉986028039
P粉986028039 2024-02-17 20:05:04
0
1
302

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粉986028039
P粉986028039

全部回覆(1)
P粉447495069

當您處理來自 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;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板