Как я могу отсортировать таблицу по "DateAdded" в компоненте таблицы пользовательского интерфейса материала для React Js? - PullRequest
0 голосов
/ 27 марта 2019

В моем проекте React я использую Table Component of Material UI.У меня есть несколько столбцов в том, что включает запись, добавленную на эту дату.Как я могу отсортировать свою таблицу по дате добавления записи?Я получаю метку времени UNIX и преобразую ее в формат мм / дд / гггг для удобства чтения.

Я использую компонент Materila -ui Table: https://material -ui.com / demos / tables /

Я пытался передать массив дат для сортировки функции, но это не сработало, так как он ожидает массив со всеми столбцами.

Ожидаемое поведение таково, когда я нажимаю наЗначок сортировки рядом с колонкой добавленной даты, она должна сортировать таблицу по дате добавления по возрастанию или по убыванию.

function desc(a, b, orderBy) {
  console.log(a.addedDate)
  if (b.addedDate < a.addedDate) {
    console.log(b.addedDate)
    return -1;
  }
  if (b.addedDate > a.addedDate) {
    return 1;
  }
  return 0;
}

    function stableSort(array, cmp) {
      const stabilizedThis = array.map((el, index) => [el, index]);
      stabilizedThis.sort((a, b) => {
        const order = cmp(a[0], b[0]);
        if (order !== 0) return order;
        return a[1] - b[1];
      });
      return stabilizedThis.map(el => el[0]);
    }

    function getSorting(order, orderBy) {
      return order === 'desc' ? (a, b) => desc(a, b, orderBy) : (a, b) => 
    -desc(a, b, orderBy);
    }

    const rows = [
      { id: 'id', numeric: false, label: 'ID'},
      { id: 'lastname', numeric: true, label: 'lastname' },
      { id: 'firstname', numeric: true, label:'firstname' },
      { id: 'email', numeric: true, label: 'email'},
      { id: 'dateadded', numeric: true, label: 'dateadded' }
     ];


    class EnhancedTableHead extends React.Component {
      createSortHandler = property => event => {
        this.props.onRequestSort(event, property);
      };

      render() {
        const { onSelectAllClick, order, orderBy, numSelected, rowCount } 
    = this.props;

    return (
      <TableHead>
        <TableRow>
          <TableCell padding="checkbox">
            <Checkbox
              indeterminate={numSelected > 0 && numSelected < rowCount}
              checked={numSelected === rowCount}
              onChange={onSelectAllClick}
            />
          </TableCell>
          {rows.map(
            row => (
              <TableCell
                key={row.id}
                align={row.numeric ? 'right' : 'left'}
                padding={row.disablePadding ? 'none' : 'default'}
                sortDirection={orderBy === row.id ? order : false}
              >
                <Tooltip
                  title="Sort"
                  placement={row.numeric ? 'bottom-end' : 'bottom-start'}
                  enterDelay={300}
                >
                  <TableSortLabel
                    active={orderBy === row.id}
                    direction={order}
                    onClick={this.createSortHandler(row.id)}
                  >
                    {row.label}
                  </TableSortLabel>
                </Tooltip>
              </TableCell>
            ),
            this,
          )}
        </TableRow>
      </TableHead>
    );
      }
    }

My Table Body looks like following:

     <TableBody>
                  {stableSort(data, getSorting(order, orderBy).slice(page* rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map(n => {
                  var convertedTimeStamp;
                  var d = new Date(n.addedDate);
                  convertedTimeStamp = d.toLocaleDateString();
                  if (n.nuid.indexOf(this.state.filterText) === -1 ) {
                    return;
      }
                  return (
                    <TableRow
                      hover

                      tabIndex={-1}
                      key={n.id}
                    >
                      <TableCell padding="checkbox">
                      </TableCell>
                      <TableCell component="th" scope="row" padding="none">
                          {n.id}
                      </TableCell>
                      <TableCell align="left">{n.lastName}</TableCell>
                      <TableCell align="left">{n.firstName}</TableCell>
                      <TableCell align="left">{n.email}</TableCell>
                      <TableCell align="right">{convertedTimeStamp} . 
   </TableCell>

                        </TableRow>
                      );
                    })}

            </TableBody>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...