reactjs 具有特定日期列的可排序React材料UI表

kd3sttzy  于 2023-06-05  发布在  React
关注(0)|答案(3)|浏览(372)

我有一个react material UI表,显示一些数据。我希望能够根据最新的日期记录对表进行排序,是否有默认的方法?

<TableHead style={{ backgroundColor: "lightgrey" }}>
              <TableRow>
                <TableCell>Location</TableCell>
                <TableCell align="right">Slot-Time </TableCell>

                <TableCell align="right" ><TableSortLabel onClick={() => handleSort('fromDate')}>From Date</TableSortLabel></TableCell>

                <TableCell align="right">From Time</TableCell>
                <TableCell align="right">To Date</TableCell> 
                <TableCell align="right">To Time</TableCell>
                <TableCell align="right">Days in Week</TableCell>
                <TableCell> </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {resultTable &&
                resultTable.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).sort(order === 'asc'? ascCompare: desCompare ).map((n) => {
                  return (
                    <TableRow key={n.id}>
                      <TableCell>
                       { facilitiesList ? getFacilityName(n.facilityId) : ""} 
                      </TableCell>
                      <TableCell align="right">{n.slotTime}</TableCell>
                      <TableCell align="right">{Moment(n.fromDate, "DD-MM-YYYY").format("MMMM Do YYYY")} </TableCell>
                      <TableCell align="right">{n.fromTime}</TableCell>
                      <TableCell align="right">{Moment(n.toDate, "DD-MM-YYYY").format("MMMM Do YYYY")}</TableCell>
                      <TableCell align="right">{n.toTime}</TableCell>
                      <TableCell align="right">
                        {n.daysOfWeek
                          .split(",")
                          .map((day) => {
                            return days[parseInt(day) - 1];
                          })
                          .join()}
                      </TableCell>`
6uxekuva

6uxekuva1#

function compare(a, b) {
  if (a.date is less than b.date) { // u can convert date into second to compare
    return -1;
  }
  if (a.date is greater than b.date ) {
    return 1;
  }
  // a.date must be equal to b.date
  return 0;
}

并修复:

...resultTable.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).sort(compare).map...
lh80um4z

lh80um4z2#

我认为在把数据发送到客户端之前,你应该把服务器上的数据排序

oyjwcjzk

oyjwcjzk3#

**你可以使用compare函数对特定的列进行排序。**通常,我们根据日期对数组进行排序,就像这样new Date(b) - new Date(a)。添加valueOf()以避免TS错误。

function descendingComparator(a, b, orderBy) {
  if (orderBy === 'date') {
    return (new Date(b[orderBy]).valueOf() - new Date(a[orderBy]).valueOf());
  }
  if (b[orderBy] < a[orderBy]) return -1;
  if (b[orderBy] > a[orderBy]) return 1;
  return 0;
}

相关问题