如何为Material UI表中的每一行添加自动增量

问题描述 投票:0回答:2

我正在通过从 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'
      },
    ]
}

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;

结果是这样的:

reactjs mongodb next.js material-ui mui-datatable
2个回答
1
投票

在 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, appointment: data.appointment.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" },
];

1
投票

您可以修改@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()).appointment);
    }

    fetchData();
  }, []);

  ...

}

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.