首页 > 解决方案 > React - 在 Map() 方法中对表列进行排序

问题描述

当我的表头数据放在 .map() 方法中时,我正在尝试对表进行排序(升序/降序)(请参阅本文中代码框链接的第 73 行)。

我可以让手形表情符号更改 onClick,但不会进行排序。我认为这可能与将对象传递给 map 方法有关,而不是在我基于此功能的代码框中找到的单个字符串或数值。这是我建模的原始沙箱: https ://codesandbox.io/embed/table-sorting-example-ur2z9?fontsize=14&hidenavigation=1&theme=dark

...这是我需要排序的数据结构的代码框: https ://codesandbox.io/s/table-sorting-example-forked-dofhj?file=/src/App.js

为了使每列可排序,我可以更改什么?任何帮助/建议将不胜感激。

应用程序.js

import React from "react";
import "./styles.css";
import {
  Button,
  Table,
  Thead,
  Tbody,
  Flex,
  Tooltip,
  Tr,
  Th,
  Td
} from "@chakra-ui/react";

//Table Headers
const TABLE_HEADERS = [
  { name: "ID Number" },
  { name: "User Type" },
  { name: "User Category" },
  { name: "User Interest" }
];

const useSortableData = (items, config = null) => {
  const [sortConfig, setSortConfig] = React.useState(config);

  const sortedItems = React.useMemo(() => {
    let sortableItems = [...items];
    if (sortConfig !== null) {
      sortableItems.sort((a, b) => {
        if (a[sortConfig.key] < b[sortConfig.key]) {
          return sortConfig.direction === "ascending" ? -1 : 1;
        }
        if (a[sortConfig.key] > b[sortConfig.key]) {
          return sortConfig.direction === "ascending" ? 1 : -1;
        }
        return 0;
      });
    }
    return sortableItems;
  }, [items, sortConfig]);

  const requestSort = (key) => {
    let direction = "ascending";
    if (
      sortConfig &&
      sortConfig.key === key &&
      sortConfig.direction === "ascending"
    ) {
      direction = "descending";
    }
    setSortConfig({ key, direction });
  };

  return { items: sortedItems, requestSort, sortConfig };
};

const ProductTable = (props) => {
  const { items, requestSort, sortConfig } = useSortableData(
    props.myUserErrorTypes
  );

  const getClassNamesFor = (name) => {
    if (!sortConfig) {
      return;
    }
    return sortConfig.key === name ? sortConfig.direction : undefined;
  };
  return (
    <Table>
      <caption>User Error Types</caption>
      <Thead>
        <Tr>
          {TABLE_HEADERS.map(({ name, description, isNumeric }) => (
            <Th key={name} isNumeric={isNumeric}>
              <Button
                type="button"
                onClick={() => requestSort(name)}
                className={getClassNamesFor(name)}
              >
                <Tooltip label={description} aria-label={description}>
                  {name}
                </Tooltip>
              </Button>
            </Th>
          ))}
        </Tr>
      </Thead>
      <Tbody>
        {items.map((error) => {
          const { userNumber, userType, errorId, errorCategory } = error;
          return (
            <React.Fragment key={errorId}>
              <Tr id={errorId} key={errorId}>
                <Td>{userNumber}</Td>
                <Td>{userType}</Td>
                <Td>{errorId}</Td>
                <Td>{errorCategory}</Td>
                <Td textAlign="center">
                  <Flex justify="justifyContent"></Flex>
                </Td>
              </Tr>
            </React.Fragment>
          );
        })}
      </Tbody>
    </Table>
  );
};

export default function App() {
  return (
    <div className="App">
      <ProductTable
        myUserErrorTypes={[
          {
            userNumber: 1234567890,
            userType: "SuperUser",
            errorId: 406,
            errorCategory: "In-Progress"
          },
          {
            userNumber: 4859687937,
            userType: "NewUser",
            errorId: 333,
            errorCategory: "Complete"
          }
        ]}
      />
    </div>
  );
}

标签: javascriptreactjssortingchakra-ui

解决方案


'ID Number'由于您使用该名称调用,因此这些项目按表头名称(例如)排序requestSortid将属性添加到与数据对象中TABLE_HEADERS的属性名称(例如)匹配的数组userNumber中的对象,并将其作为参数传递给requestSortgetClassNamesFor函数。

const TABLE_HEADERS = [
  { name: 'ID Number', id: 'userNumber' },
  { name: 'User Type', id: 'userType' },
  { name: 'User Category', id: 'errorId' },
  { name: 'User Interest', id: 'errorCategory' },
]
{
  TABLE_HEADERS.map(({ name, id }) => (
    <Th key={id}>
      <Button
        type="button"
        onClick={() => requestSort(id)}
        className={getClassNamesFor(id)}
      >
        {name}
      </Button>
    </Th>
  ))
}

您还尝试使用标头对象中的descriptionandisNumeric值,但它们都是undefined. 您可能希望将这些属性添加到TABLE_HEADERS数组中的对象。

在 CodeSandbox 上编辑


推荐阅读