十二、使用fetch获取数据

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

  • fetch() 用于向服务器发送请求加载数据,是 Ajax 的升级版
  • 需要两个参数
    • 请求地址
    • 请求信息

(一) src/index.js

import ReactDOM from "react-dom/client";
import { App } from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(<App />);

(二) 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数据替换为从接口 http://localhost:1337/api/students 中获取到的数据
    组件初始化时需要向服务器发送请求来加载数据
  */
  useEffect(() => {
    // 加载数据
    fetch("http://localhost:1337/api/students")
      .then((response) => {
        // response表示响应信息
        // console.log(response);
        // 将响应的json直接转换为js对象
        return response.json();
      })
      .then((data) => {
        // console.log(data);
        setStuData(data.data);
      })
      .catch((err) => {
        alert(err);
      });
  }, []);

  return (
    <div className="app">
      <StudentList students={stuData} />
    </div>
  );
};

(三) src/App.css

.app {
  margin: 100px auto;
  background-color: lightcoral;
  width: max-content;
  padding: 10px;
}
table {
  border-collapse: collapse;
}
tr {
  border: 1px solid #eee;
}
td {
  color: #fff;
  width: 50px;
  border: 1px solid #eee;
  text-align: center;
}

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

import React from "react";

export const Student = ({ stu: { name, age, gender, address } }) => {
  return (
    <tr>
      <td>{name}</td>
      <td>{age}</td>
      <td>{gender}</td>
      <td>{address}</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>
        </tr>
      </thead>
      <tbody>
        {props.students.map((stu) => {
          return <Student key={stu.id} stu={stu.attributes} />;
        })}
      </tbody>
    </table>
  );
};
上次编辑于: