1

我有一个显示一些数据的反应材料 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>`
4

3 回答 3

2
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...
于 2020-05-22T09:59:08.000 回答
0

您可以使用比较功能对特定列进行排序。一般来说,我们按照日期对数组进行排序是这样的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;
}
于 2021-07-28T11:21:34.047 回答
0

我认为您应该先对服务器上的数据进行排序,然后再将其发送到客户端

于 2020-05-22T12:34:19.113 回答