首页 > 解决方案 > 反应表排序

问题描述

我已经开始学习 React。我无法对反应表进行排序。我遵循材料 UI 分页、排序和过滤,当我执行控制台日志(a[order] > b[order])或控制台日志(a[order] < b[order])时,它会抛出未定义

下面是我的代码。

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

    return stabilizedThis.map((el) => el[0]);
  }

  function getComparator(order, orderBy) {
    //console.log(order, orderBy);
    if (order === 'desc') {
      return (a, b) => descendingComparator(a, b, orderBy);
    } else {
      return (a, b) => -descendingComparator(a, b, orderBy);
    }

  }

  function descendingComparator(a, b, orderBy) {
    // console.log(b[orderBy] > a[orderBy]);
    //console.log(a.orderBy);
    if (b[orderBy] < a[orderBy]) {
      return -1;
    }
    if (b[orderBy] > a[orderBy]) {
      return 1;
    }
    return 0;
  }

  const tablePagingAndSorting = () => {
    return stableSort(customers, getComparator(order, orderBy)).slice(page * rowsPerPage, (page + 1) * rowsPerPage);
  };


  const headCells = [
    { id: 1, text: '#' },
    { id: 2, text: 'Name' },
    { id: 3, text: 'Phone' },
    { id: 4, text: 'Email' },
    { id: 5, text: 'Action' },
  ];

  const handleSortRequest = (cellId) => {
    const isAsc = orderBy == cellId && order == 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(cellId);
  };

桌子 :

  {headCells.map((headCell, index) => {
              return (
                <TableCell key={headCell.id} align='center'>
                  <TableSortLabel active={orderBy == headCell.id} direction={orderBy == headCell.id ? order : 'asc'} onClick={() => handleSortRequest(headCell.id)}>
                    {headCell.text}
                  </TableSortLabel>
                </TableCell>
              );
            })}

标签: javascriptreactjsmaterial-ui

解决方案


推荐阅读