十三、数据加载提示和处理错误

郁子大约 1 分钟约 323 字笔记React18李立超

(一) src/App.jsx

import React, { useEffect, useState } from "react";
import { StudentList } from "./components/StudentList";
import "./App.css";

// const STU_DATA = [
//   {
//     id: "1",
//     attributes: {
//       name: "张三",
//       age: 18,
//       gender: "男",
//       address: "aaa",
//     },
//   },
//   {
//     id: "2",
//     attributes: {
//       name: "李四",
//       age: 28,
//       gender: "女",
//       address: "bbb",
//     },
//   },
//   {
//     id: "3",
//     attributes: {
//       name: "王五",
//       age: 38,
//       gender: "男",
//       address: "ccc",
//     },
//   },
// ];

export const App = () => {
  // 学生数据
  // const [stuData, setStuData] = useState(STU_DATA);
  const [stuData, setStuData] = useState([]);
  // 记录数据是否正在加载
  const [loading, setLoading] = useState(false);
  // 记录错误信息
  const [error, setError] = useState(null);

  useEffect(() => {
    // 加载数据
    setLoading(true);
    setError(null);
    fetch("http://localhost:1337/api/students")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setStuData(data.data);
        setLoading(false);
      })
      .catch((err) => {
        alert(err);
      });

    // 模拟请求出错
    // fetch("http://localhost:1337/api/student")
    //   .then((response) => {
    //     // 判断是否正常返回响应信息
    //     if (response.ok) return response.json();
    //     // 没有成功加载到数据
    //     setLoading(false);
    //     // 抛出错误
    //     throw new Error("数据加载失败");
    //   })
    //   .then((data) => {
    //     setStuData(data.data);
    //     setLoading(false);
    //   })
    //   .catch((err) => {
    //     // catch一执行,说明上述代码出错了
    //     // 统一处理错误
    //     setLoading(false);
    //     setError(err);
    //   });
  }, []);

  return (
    <div className="app">
      {!loading && !error && <StudentList students={stuData} />}
      {loading && <p>数据正在加载中...</p>}
      {error && <p>数据加载异常!</p>}
    </div>
  );
};
上次编辑于: