由于某种原因,我的代码只显示一次,当我刷新页面时,我开始出现错误
P粉986028039
P粉986028039 2024-02-17 20:05:04
0
1
322

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;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板