我正在通过从 Material UI 创建表并从 MongoDB 获取数据来构建 Next.js 项目。如何操作表中的数据?
我想要“#”列在每一行中具有从 1、2、3、4、5 等开始的自动递增值。
这是我的代码:
数据模型:
{
appointment: [
{
_id: '6609339e8891194adf3beb60',
name: 'tuyi',
date: '2024-03-31',
phone: '45454',
terapist: 'fdgdf',
statust: 'done'
},
]
}
页面.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;
结果是这样的:
在 MongoDB 中,
_id
大部分是单调递增的十六进制字符串。但是,由于您只希望显示带有数字 ID 的项目,因此您可以在完成从 API 获取数据后对数据进行预处理。对于您的情况,您可以在从 API 获取 JSON 后执行此操作:
您可以在响应作为 @AngYC 的答案返回时修改数据,也可以自定义
column.id
模板中索引的显示值。请注意,您需要更改数组中的索引变量
columns
,以j
避免i
与appointment
.我怀疑是否可以使用
async
. 您将收到此错误:对象作为 React 子项无效 (found: [object Promise])。所以你必须使用 React hooks:
useState
和useEffect
函数,如下所示:演示@StackBlitz