搜索

首页  >  问答  >  正文

由于某种原因,我的代码只显示一次,当我刷新页面时,我开始出现错误

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粉986028039288 天前325

全部回复(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
  • 取消回复