十五、删除数据

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

(一) src/App.jsx

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

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

  const fetchData = useCallback(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);
    }
  }, []);

  // useEffect()参数不能是异步函数
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const loadData = () => {
    fetchData();
  };

  return (
    <StudentContext.Provider value={{ fetchData }}>
      <div className="app">
        <button onClick={loadData}>加载数据</button>
        {!loading && !error && <StudentList students={stuData} />}
        {loading && <p>数据正在加载中...</p>}
        {error && <p>数据加载异常!</p>}
      </div>
    </StudentContext.Provider>
  );
};

(二) src/components/Student/index.jsx

import React, { useCallback, useContext, useState } from "react";
import StudentContext from "../../store/StudentContext";

export const Student = ({
  stu: {
    id,
    attributes: { name, age, gender, address },
  },
}) => {
  /*
    props = {
      stu: {
        id: xxx,
        attributes: {
          name,age,gender,address
        }
      }
    }
  */

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const ctx = useContext(StudentContext);

  const delStu = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch(`http://localhost:1337/api/students/${id}`, {
        method: "delete",
      });
      if (!res.ok) throw new Error("删除失败!");
      ctx.fetchData();
    } catch (error) {
      setError(error);
    } finally {
      setLoading(false);
    }
  }, [id, ctx]);

  const deleteStudent = () => {
    delStu();
  };

  return (
    <>
      <tr>
        <td>{name}</td>
        <td>{age}</td>
        <td>{gender}</td>
        <td>{address}</td>
        <td>
          <button onClick={deleteStudent}>删除</button>
        </td>
      </tr>

      {loading && (
        <tr>
          <td colSpan={5}>正在删除数据...</td>
        </tr>
      )}
      {error && (
        <tr>
          <td colSpan={5}>删除失败!</td>
        </tr>
      )}
    </>
  );
};

(三) src/components/StudentList/index.jsx

import React from "react";
import { Student } from "../Student";

export const StudentList = (props) => {
  return (
    <table>
      <caption>学生列表</caption>
      <thead>
        <tr>
          <th>姓名</th>
          <th>性别</th>
          <th>年龄</th>
          <th>地址</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        {props.students.map((stu) => {
          return <Student key={stu.id} stu={stu} />;
        })}
      </tbody>
    </table>
  );
};

(四) src/store/StudentContext.js

import React from "react";

const StudentContext = React.createContext({
  fetchData: () => {},
});

export default StudentContext;
上次编辑于: