TableHead не сортируется по запросу - PullRequest
0 голосов
/ 04 июля 2019

У меня есть таблица, в которой есть кликабельные заголовки строк, которые позволяют пользователю сортировать таблицу на основе функции onRequestSort, которую вы увидите ниже. Однако это в настоящее время не работает правильно, я использую reactHooks , чтобы сделать handleRequestSort, и я, возможно, допустил ошибку по пути, любой совет был бы хорош. Ниже мой компонент поставщиков

    export const desc = (a, b, orderBy) => {
      if (b[orderBy] < a[orderBy]) {
      return -1;
     }
    else if (b[orderBy] > a[orderBy]) {
     return 1;
    }
    else {
     return 0;
    }
     };

    export const stableSort = (array, cmp) => {
      if (array) {
       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]);
    }
      else return [];
    };

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


    const SuppliersTable = (props) => {
    const [page, setPage] = useState(0);
    const [rowsPerPage, setRowsPerPage] = useState(5);
    const [order, setOrder] = useState('desc');
    const [orderBy, setOrderBy] = useState('');

    const handleChangePage = (event, page) => {
     setPage({ page });
    };

    const handleChangeRowsPerPage = event => {
     setRowsPerPage({ rowsPerPage: event.target.value });
    };

    const handleRequestSort = (event, property) => {
      const orderBy = property;
      let order = 'desc';

      if (orderBy === property && order === 'desc') {
      order = 'asc';
    }
    setOrder('desc');
    setOrderBy('asc');
    };



     const handleClick = (id) => {
         props.history.push(`/suppliers/${id}/details`);
       };


  const { classes, filteredSuppliers } = props;
  const emptyRows = rowsPerPage - Math.min(rowsPerPage, filteredSuppliers.length - page * rowsPerPage);
  return (
    <Paper className={classes.root}>
      <div className={classes.tableWrapper}>
        <Table className={classes.table} aria-label="tableTitle" id="suppliersTable">
          <SuppliersTableHead
            order={order}
            orderBy={orderBy}
            onRequestSort={handleRequestSort}
            rowCount={filteredSuppliers.length}
          />
          <TableBody aria-label="suppliers Table">
            {stableSort(filteredSuppliers, getSorting(order, orderBy))
              .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              .map(supplier => {
                return (
                  supplier.addressInfo.map(row => (
                    <TableRow className={classes.tableRow}
                      hover={true}
                      // onClick={() => { handleClick(supplier.id); }} for a later ticket
                      tabIndex={0}
                      key={row.id}
                    >
                      <TableCell component="th" scope="row" padding="none">{supplier.name}</TableCell>
                      <TableCell padding="none">{row.officeName}</TableCell>
                      <TableCell padding="none">{row.officeEmail}</TableCell>
                      <TableCell padding="none">{row.officeTelephone}</TableCell>
                      <TableCell padding="none">{row.town}</TableCell>
                      <TableCell padding="none">{row.county}</TableCell>
                      <TableCell padding="none">{row.postcode}</TableCell>
                    </TableRow>
                  ))
                );
              })}
            {emptyRows > 0 && (
              <TableRow style={{ height: 49 * emptyRows }}>
                <TableCell colSpan={8} />
              </TableRow>
            )}
          </TableBody>
        </Table>
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={filteredSuppliers.length}
          rowsPerPage={rowsPerPage}
          page={page}
          backIconButtonProps={{
            'aria-label': 'Previous Page',
          }}
          nextIconButtonProps={{
            'aria-label': 'Next Page',
          }}
          onChangePage={handleChangePage}
          onChangeRowsPerPage={handleChangeRowsPerPage}
        />
      </div>
    </Paper>
  );
};

и мой компонент таблицы

    const rows = [
    { id: 'title', numeric: false, disablePadding: true, label: 'Title' },
    { id: 'office', numeric: false, disablePadding: true, label: 'Office' },
    { id: 'email', numeric: false, disablePadding: true, label: 'Email' },
    { id: 'telephone', numeric: false, disablePadding: true, label: 'Telephone' },
    { id: 'town', numeric: false, disablePadding: true, label: 'Town' },
    { id: 'county', numeric: false, disablePadding: true, label: 'County' },
    { id: 'postCode', numeric: false, disablePadding: true, label: 'Post Code' },
];

const SuppliersTableHead = props => {
    const createSortHandler = property => {
        return event => {
            props.onRequestSort(event, property);
        };
    };
    const { order, orderBy } = props;

    return (
        <TableHead>
            <TableRow>
                {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={createSortHandler(row.id)}
                            >
                                {row.label}
                            </TableSortLabel>
                        </Tooltip>
                    </TableCell>
                ))}
            </TableRow>
        </TableHead>
    );
};

SuppliersTableHead.propTypes = {
    onRequestSort: PropTypes.func.isRequired,
    order: PropTypes.string.isRequired,
    orderBy: PropTypes.string.isRequired,
    rowCount: PropTypes.number.isRequired,
};

1 Ответ

0 голосов
/ 04 июля 2019

Похоже, вам нужно передать ваш заказ:

<SuppliersTableHead
        order={order}
        orderBy={orderBy}
        onRequestSort={()=>handleRequestSort(orderBy)}
        rowCount={filteredSuppliers.length}
      />

const handleRequestSort = (orderBy) => {
  // update your sort here 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...