我正在构建 nextjs 项目并从 Material ui 创建表并从 mongoDB 获取数据。如何操作表中的数据。我想要 # 列自动递增,每行从 1,2,3,4,5 等开始。
这是我的代码
数据模型:
{
_id: '6609339e8891194adf3beb60'
name: 'tuyi',
date: '2024-03-31',
phone: '45454',
terapist: 'fdgdf',
statust: 'done'
},
page.jsx
async function getAppointment() {
const res = await fetch("http://localhost:3000/api/appointment", {
method: "GET",
cache: "no-store",
});
// const data = await res.json();
return res.json();
}
async function Appointment() {
const { appointment } = await getAppointment();
const columns = [
{ id: "_id", name: "#" },
{ id: "name", name: "Nama" },
{ id: "date", name: "Tanggal" },
{ id: "phone", name: "No Telp." },
{ id: "terapist", name: "Terapis" },
{ id: "statust", name: "Status" },
];
return (
<TableContainer>
<Table>
<TableHead>
<TableRow>
{columns.map((column) => (
<TableCell key={column.id}>{column.name}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{appointment &&
appointment.map((row, i) => {
return (
<TableRow key={i}>
{columns &&
columns.map((column, i) => {
let value = row[column.id];
return <TableCell key={value}>{value}</TableCell>;
})}
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
</div>
);
}
export default Appointment;
结果是这样的:
我想要 # 列自动递增,每行从 1,2,3,4,5 等开始。
在 MongoDB 中,
_id
主要是单调递增的十六进制字符串。但是,由于您只想显示带有数字 ID 的项目,因此您可以在完成从 API 获取数据后对数据进行预处理。
就您而言,您可以在从 API 获取 JSON 后执行此操作:
async function getAppointment() {
const res = await fetch("http://localhost:3000/api/appointment", {
method: "GET",
cache: "no-store",
});
const data = await res.json();
// Here, you can add a numerically increasing index/ID to all the items
return data.map((row, index) => ({ ...row, index: index + 1 });
}
// After that, change the following to read from `index` key instead
const columns = [
{ id: "index", name: "#" },
{ id: "name", name: "Nama" },
{ id: "date", name: "Tanggal" },
{ id: "phone", name: "No Telp." },
{ id: "terapist", name: "Terapis" },
{ id: "statust", name: "Status" },
];
您可以修改@AngYC的答案返回时的数据,也可以通过模板中的
column.id
自定义索引的显示值。
请注意,您需要将
columns
数组中的索引变量更改为 j
,以避免变量名称与 i
中的 appointment
冲突。
{appointment &&
appointment.map((row, i) => {
return (
<TableRow key={i}>
{columns &&
columns.map((column, j) => {
let value = column.id == '_id' ? i + 1 : row[column.id];
return <TableCell key={value}>{value}</TableCell>;
})}
</TableRow>
);
})}
我怀疑是否可以使用
async
创建 React 组件。您将收到此错误:对象作为 React 子对象无效(找到:[object Promise])。
所以你必须使用 React hooks:
useState
和 useEffect
函数如下:
import { useState, useEffect } from 'react';
export function Appointment() {
const [appointment, setAppointment] = useState([]);
useEffect(() => {
async function fetchData() {
setAppointment(await getAppointment());
}
fetchData();
}, []);
...
}