未显示React数据

时间:2020-04-16 12:20:55

标签: reactjs axios use-state

我试图显示存储在countries列表中的这些数据,但是,这导致我的表中什么也没有得到。问题很可能是由于Table不能正确地重新呈现所致,我尝试在第14行使用useEffect打印列表的长度,并且确实得到了正确的结果。任何提示将不胜感激!

import React, { useState, useEffect } from "react";
import getData from "../Hooks/getData";
import Table from "react-bootstrap/Table";

const Lists = () => {
  const [countries, setCountries] = useState([]);

  if (countries.length === 0) {
    getData().then((data) => {
      setCountries(data.data.Countries);
    });
  }

  useEffect(() => {
    console.log(countries.length);
  });

  const getInfo = () => {
    countries.map((country) => {
      return (
        <tr>
          <td>{country.Country}</td>
          <td>{country.NewConfirmed}</td>
          <td>{country.TotalConfirmed}</td>
        </tr>
      );
    });
  };

  return (
    <Table striped bordered hover>
      <thead>
        <tr>
          <th>Country Name</th>
          <th>New Confirmed</th>
          <th>Total Confirmed</th>
        </tr>
      </thead>
      <tbody>{getInfo()}</tbody>
    </Table>
  );
};

export default Lists;

1 个答案:

答案 0 :(得分:3)

您的getInfo不返回任何内容。

要么通过在函数主体周围不使用{}来使用隐式返回,要么显式使用return语句

 const getInfo = () => countries.map((country) => {
      return (
        <tr>
          <td>{country.Country}</td>
          <td>{country.NewConfirmed}</td>
          <td>{country.TotalConfirmed}</td>
        </tr>
      );
    });

  const getInfo = () => {
    return countries.map((country) => {
      return (
        <tr>
          <td>{country.Country}</td>
          <td>{country.NewConfirmed}</td>
          <td>{country.TotalConfirmed}</td>
        </tr>
      );
    });
  };