即使没有语法错误也没有警告,为什么元素没有被渲染?

Why isn't the element getting rendered even though there is no syntax error nor warning?

我从 Hltv API 中获取了 CSGO 的前 30 名队伍。数据存储在 team 变量中,我使用映射函数从数组中获取各个团队的名称并进行渲染。但是,它目前没有渲染任何东西。

import React from 'react';
import './App.css';
import HLTV from 'hltv';

function App() {

  const get = async () => {
    return await HLTV.getTeamRanking()
      .then(res => Object.entries(res))
      .catch(err => console.log(err));
  }

  const teamNames = [];

  (async () => {
    const teams = await get();

    teams.map(x => {
      teamNames.push(x[1].team.name);
    });

    teamNames.map(team => {
      console.log(team);
    })
  })();

  return (
    <ul>
      {teamNames.map(team => <li>{team}</li>)}
    </ul>
  )
}

export default App;

React 不知道 teamMates 变量正在更新。为了让 React 知道变量的变化,您应该在渲染组件之前获取数据或使用 useStateuseEffect.

您可以阅读 useState documentation 了解更多信息。

import React, { useState, useEffect } from 'react';
import './App.css';
import HLTV from 'hltv';

const get = async () => {
  return await HLTV.getTeamRanking()
    .then(res => Object.entries(res))
    .catch(err => console.log(err));
}

function App() {
  const [teamNames, setTeamNames] = useState([]);

  useEffect(() => {
    get().then(teams => {
      setTeamNames(teams.map(x => x[1].team.name));
    });
  }, []);

  return (
    <ul>
      {teamNames.map(team => <li>{team}</li>)}
    </ul>
  )
}

它不会呈现,因为对于初始呈现来说结果到达得太晚。将 teamNames 更改为有状态的,例如const [teamNames, setTeamNames ] = useState([])。然后用 setTeamNames 更新传入的结果。而不是 IIFE(立即调用的函数表达式),使用 useEffect(() => {...}).

例如:

function App() {

  const [teamNames, setTeamNames] = useState([]);
  React.useEffect(() => {
    const fetchTeamRankings = async () => {
      return HLTV.getTeamRanking()
        .then(res => Object.entries(res))
        .catch(err => console.log(err));
      };
      fetchTeamRankings().then(result => setTeamNames(result.map( r => r[1].team.name  )));
  }, [setTeamNames]);

  return (
    <ul>
      {teamNames.map(team => <li>{team}</li>)}
    </ul>
  )
}