十六、添加数据
大约 1 分钟约 315 字
src/components/StudentList/index.jsx
(一) import React from "react";
import Student from "../Student";
import StudentForm from "../StudentForm";
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>
<tfoot>
<StudentForm />
</tfoot>
</table>
);
};
export default StudentList;
src/components/StudentForm/index.jsx
(二) import React, { useCallback, useContext, useState } from "react";
import StudentContext from "../../store/StudentContext";
import "./index.css";
const StudentForm = () => {
const ctx = useContext(StudentContext);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [inputData, setInputData] = useState({
name: "",
gender: "男",
age: 0,
address: "",
});
const { name, gender, age, address } = inputData;
const nameChange = (e) => {
setInputData((pre) => ({ ...pre, name: e.target.value }));
};
const genderChange = (e) => {
setInputData((pre) => ({ ...pre, gender: e.target.value }));
};
const ageChange = (e) => {
setInputData((pre) => ({ ...pre, age: +e.target.value }));
};
const addressChange = (e) => {
setInputData((pre) => ({ ...pre, address: e.target.value }));
};
const addStudent = useCallback(
async (newStudent) => {
try {
setLoading(true);
setError(null);
const res = await fetch("http://localhost:1337/api/students/", {
method: "post",
body: JSON.stringify({
data: newStudent,
}),
headers: {
"Content-type": "application/json",
},
});
if (!res.ok) throw new Error("添加失败!");
ctx.fetchData();
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
},
[ctx],
);
const onSubmitAdd = () => {
addStudent(inputData);
};
return (
<>
<tr className="student-form">
<td>
<input type="text" value={name} onChange={nameChange} />
</td>
<td>
<select value={gender} onChange={genderChange}>
<option value="男">男</option>
<option value="女">女</option>
</select>
</td>
<td>
<input type="text" value={age} onChange={ageChange} />
</td>
<td>
<input type="text" value={address} onChange={addressChange} />
</td>
<td>
<button onClick={onSubmitAdd}>添加</button>
</td>
</tr>
{loading && (
<tr>
<td colSpan={5}>添加中...</td>
</tr>
)}
{error && (
<tr>
<td colSpan={5}>添加失败!</td>
</tr>
)}
</>
);
};
export default StudentForm;
src/components/StudentForm/index.css
(三) .student-form input {
width: 80px;
}