使用 Lodash 和 React 对数字字符串进行排序?

Sorting Number Strings Using Lodash and React?

我正在整理我的 table 列。我的文本专栏排序良好,但数字列则不然。

当我用我试图排序的数字检查数据时,我看到了以下内容。这只是一个例子:

watchCount: ["2"]

此外,有些项目没有我需要的一些字段,在这种情况下我只显示一个0。可以在下面看到。

这是我的 table 映射数据的地方。我也只是尝试将 parseInt() 包含在数值数据中,但这无济于事。我正在尝试复制此示例:semantic ui react sort

我无法判断是我在此处进行排序时做错了什么,还是只是因为它是一个字符串而无法排序。

 <Table sortable celled fixed striped>
          <Table.Header>
            <Table.Row>
              <Table.HeaderCell
                sorted={column === "title" ? direction : null}
                onClick={() => handleSort("title")}
              >
                Card Title
              </Table.HeaderCell>
              <Table.HeaderCell
                sorted={column === "bids" ? direction : null}
                onClick={() => handleSort("bids")}
              >
                # Bids
              </Table.HeaderCell>
              <Table.HeaderCell
                sorted={column === "watch" ? direction : null}
                onClick={() => handleSort("watch")}
              >
                Watchers
              </Table.HeaderCell>
              <Table.HeaderCell
                sorted={column === "price" ? direction : null}
                onClick={() => handleSort("price")}
              >
                Price
              </Table.HeaderCell>
              <Table.HeaderCell
                sorted={column === "time" ? direction : null}
                onClick={() => handleSort("time")}
              >
                Time Left
              </Table.HeaderCell>
            </Table.Row>
          </Table.Header>
          <Table.Body>
            {_.map(filteredData, card => (
              <>
                <Table.Row key={card.id}>
                  <Table.Cell>{card.title}</Table.Cell>
                  <Table.Cell>
                    {parseInt(
                      card.sellingStatus[0].bidCount
                        ? card.sellingStatus[0].bidCount
                        : 0
                    )}
                  </Table.Cell>
                  <Table.Cell>
                    {parseInt(
                      card.listingInfo[0].watchCount
                        ? card.listingInfo[0].watchCount
                        : 0
                    )}
                  </Table.Cell>
                  <Table.Cell>
                    $
                    {parseInt(
                      card.sellingStatus &&
                        card.sellingStatus[0].currentPrice[0]["__value__"]
                    )}
                  </Table.Cell>
                  <Table.Cell>
                    <TimeAgo
                      date={new Date(
                        card.listingInfo && card.listingInfo[0].endTime
                      ).toLocaleDateString()}
                    />
                  </Table.Cell>
                </Table.Row>
              </>
            ))}
          </Table.Body>
        </Table>

注意,这里也是我的 handleSort 函数

 const [column, setColumn] = useState(null);
  const [direction, setDirection] = useState(null);
  const [filteredData, setData] = useState(props.cardsToShow);

  console.log("CARDS TO SHOW", props.cardsToShow);
  console.log("TYPE OF", typeof cardsToShow);
  console.log("Filtered Data", filteredData);
  console.log("column", column);
  console.log("direction", direction);

  const handleSort = clickedColumn => {
    if (column !== clickedColumn) {
      setColumn(clickedColumn);
      setData(_.sortBy(filteredData, [clickedColumn]));
      setDirection("ascending");
      return;
    }

    setData(_.sortBy(filteredData.reverse()));
    direction === "ascending"
      ? setDirection("descending")
      : setDirection("ascending");
  };

已编辑代码

const handleSortNumeric = clickedColumn => {
    const sorter = data => ~~data[clickedColumn];
    setData(_.sortBy(filteredData, sorter));
  };

  const handleSortReverse = () => {
    const sorter = data => ~~data;
    setData(_.sortBy(filteredData.reverse(), sorter));
  };

  const handleSort = clickedColumn => {
    if (column !== clickedColumn) {
      setColumn(clickedColumn);
      // setData(_.sortBy(filteredData, [clickedColumn]));
      handleSortNumeric(clickedColumn);
      setDirection("ascending");
      return;
    }

    // setData(_.sortBy(filteredData.reverse()));
    handleSortReverse();
    direction === "ascending"
      ? setDirection("descending")
      : setDirection("ascending");
  };

字符串排序将遵循 Unicode 顺序,它们按字符排序,而不是作为一个数字整体排序。因此,在对“40”和“5”进行排序时,您会期望“5”排在第一位,但“40”中的“4”是与之比较并丢失的。

详情请见此处: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

就直接解决您的问题而言,您可以将 _.sortBy() 函数作为第二个参数传递,并在函数中将值转换为数字(使用 ~~Number(), parseInt(), 等等)以避免字符串比较。

由于您似乎对这些进行了硬编码,因此您还可以使用单独的 handleSort 函数来分离问题:

const handleSortNumeric = ( clickedColumn ) => {
    // ...

    const sorter = data => ~~data[ clickedColumn ];
    setData(_.sortBy(filteredData, sorter));

    // ...
};

但是如果您可以控制数据从服务器呈现的方式,则应提供正确类型的数据以避免将来出现此类情况