reactjs 数组出现在console.log()中,但不会在react中呈现?使用useEffect挂钩

deikduxw  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(123)
import React, { useEffect, useState } from "react";
import { useGetTeamQuery } from "./store/teamsApi"

function TeamList(props) {
    const team_names = []
    console.log("GET ALL TEAMS", props.props.items)
    

    useEffect(() => {
        const fetchData = async () => {
            for (let i = 1; i < 31; i++) {
                const res = await fetch(
                    `http://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/teams/${i}?lang=en&region=us`
                    );
                const json = await res.json();
                console.log("JSON", json)
                team_names.push(json.displayName)
        }};
        fetchData();

        }, [team_names]);
    console.log("DATA", team_names)

    return (
        <>
        <div className="container">
            <h1>Team List</h1>
            <div>
            <ol>
                {console.log("DATA 2", team_names)}
                {team_names.map(team => (
                    <li>{team}</li>
                ))}
            </ol>
            </div>
        </div>
        </>
    )
}

export default TeamList;

没有错误,但没有代码呈现在标记之外。
我尝试过使用许多标签,也尝试过对useeffect函数进行不同的修改。因为列表显示的是“DATA 2”console.log,所以我认为问题出在下面的代码块上。我不知道如何重新表达这个Map:

{team_names.map(team => (
                    <li>{team}</li>
                ))}
eeq64g8w

eeq64g8w1#

您应该使用useState保存来自API的响应。
下面是您的解决方案:

import React, { useEffect, useState } from "react";
import { useGetTeamQuery } from "./store/teamsApi";

function TeamList(props) {
  const [team_names, setTeam_names] = useState([]);

  useEffect(() => {
    let arr = [];
    async function fetchData() {
      try {
        for (let i = 1; i < 31; i++) {
          const response = await fetch(
            `https://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/teams/${i}?lang=en&region=us`
          );
          const json = await response.json();
          arr.push(json.displayName);
        }
      } catch (e) {
        console.error(e);
      }
      setTeam_names(arr);
    }
    fetchData();
  }, []);

  return (
    <>
      <div className="container">
        <h1>Team List</h1>
        <div>
          <ol>
            {team_names.map((team, i) => (
              <li key={i}>{team}</li>
            ))}
          </ol>
        </div>
      </div>
    </>
  );
}

export default TeamList;

它在codesandbox中实时显示:https://codesandbox.io/s/admiring-liskov-1vmzd7?file=/src/TeamList.js

相关问题