React js 按钮刷新并加载新数据集

React js button refresh and loading new set of data

我是 React js 新手。我使用 express 服务器从 open api 中获取了一个数据。我成功地将随机猫文本浏览到我的反应组件。现在我想创建一个按钮来获取一组新的猫的事实。当前端获取数据时,它必须显示一个加载微调器来代替结果。获取结果后,必须隐藏微调器并呈现结果。如果在获取数据时出现错误,则必须使用 console.log.

记录错误消息

这是我的服务器,运行良好。

const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
const axios = require("axios");
const morgan = require("morgan");
const cors = require("cors");

app.use(morgan("common"));
app.use(cors());
app.get("/cat", async (req, res, next) => {
  axios
    .get("https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=5")
    .then(response => res.send(response.data))
    .catch(err => {
      console.log(err);
      res.status(500).send(err);
    });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

这是我的 React 组件。

  import React, { useEffect, useState } from "react";

  const Home = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetchdata();
  }, []);

  const fetchdata = async () => {
    const response = await fetch("http://localhost:5000/cat");
    const data = await response.json();
    console.log(data);
    setData(data);
  };

  return (
    <div className="bg-color">
      {data.map(facts => {
        return (
          <ul>
            <li>{facts.text}</li>
          </ul>
        );
      })}
      <button>new data</button> //IN HERE I WANT to FETCH NEW DATA and showing loading spinner.
    </div>
  );
};

export default Home;

像这样更改您的组件:

import React, { useEffect, useState } from "react";

const Home = () => {
  const [data, setData] = useState([]);
  const [loadingData, setLoadingData] = useState(false);

  useEffect(() => {
    fetchdata();
  }, []);

  const fetchdata = async () => {
    setLoadingData(true);
    const response = await fetch("http://localhost:5000/cat");
    const data = await response.json();
    console.log(data);
    setData(data);
    setLoadingData(false);
  };

  return (
    <div className="bg-color">
      {data.map(facts => {
        return (
          <ul>
            <li>{facts.text}</li>
          </ul>
        );
      })}
      {!loadingData && <button onClick={() => fetchdata()}>new data</button>}
      {loadingData && <span>Loading...</span>}
    </div>
  );
};

export default Home;