十二、使用fetch获取数据
大约 1 分钟约 367 字
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>
);
};