十四、使用await

郁子小于 1 分钟约 159 字笔记React18李立超

(一) src/App.jsx

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

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

  // useEffect()参数不能是异步函数
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        const res = await fetch("http://localhost:1337/api/students");
        if (res.ok) {
          const data = await res.json();
          setStuData(data.data);
        } else {
          throw new Error("数据加载失败!");
        }
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

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