【问题标题】:React Table not sorting numbers correctly反应表没有正确排序数字
【发布时间】:2019-11-04 09:41:34
【问题描述】:

React-table 是这样对小数进行排序的:

我的猜测是,虽然我从服务器接收数字,但 react-table 将它们作为文本处理。所以,我像这样修改了访问器:

accessor: d => Number(d.Invoice_Weight).toFixed(2)

但我总是弄错排序。

这是列的代码:

 {
                      Header: () => 
                      <DropDownMenu 
                      header={content[lang].Invoice_Weight}
                      openModal = {this.onOpenSelectColumnsModal}
                      />,
                      id: 'Invoice_Weight',
                      sortable: true,
                      accessor: d => Number(d.Invoice_Weight).toFixed(2),
                      //width: 200,
                      getProps: () => {
                        return {
                          style: {
                            textAlign: 'right'
                          }
                        }
                      },
                      show: Invoice_Weight,
                    },

【问题讨论】:

    标签: reactjs react-table


    【解决方案1】:

    React Table 的默认排序方式提供了字符串排序,所以你必须使用 React Table 提供的 sortMethod props。

    sortMethod: (a, b) => {
       a = Number(a); // Converting into number
       b = Number(b); // Converting into number
       if (a.length === b.length) {
         return a > b ? 1 : -1; // same length condition
       }
       return a.length > b.length ? 1 : -1; // comparing length of string
    }
    

    【讨论】:

      【解决方案2】:

      正如其他答案中所建议的那样,问题是toFixed 返回一个字符串,因此排序将使用字符串比较来完成。但是,在这种情况下强制返回数字将不起作用,因为您将失去尾随 0s,我猜您仍然需要。

      另一种解决方案是使用自定义排序:

      accessor: d => Number(d.Invoice_Weight).toFixed(2),
      sortMethod: (a, b) => Number(a)-Number(b)
      

      您可能希望改进 sortMethod 以处理 NaN 和 Infinities(如果有的话),但这是一般的想法

      您可以使用它来将字符串强制转换为数字,但只能在排序的上下文中使用,而不影响显示的值

      【讨论】:

        【解决方案3】:

        我的猜测是这是因为.toFixed() 返回一个字符串,所以它仍然将它们排序为字符串。因此,如果您想将数字四舍五入并将其保留为小数点后两位,则必须执行以下操作:

        accessor: d => Number(Number(d.Invoice_Weight).toFixed(2))
        

        所以先转成数字,四舍五入到小数点后两位的字符串,然后再转回数字。

        【讨论】:

        • 克里斯,非常感谢!您的回答确实解决了问题,但问题是我丢失了小数点的零 (,00),所以我想我会使用 apokryfos 的解决方案。谢谢你们!
        • 没问题,在阅读了他的回答后,我意识到如果您确实需要保持尾随零,这绝对是正确的选择!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        • 2020-04-26
        • 2014-09-07
        • 2014-11-21
        • 1970-01-01
        相关资源
        最近更新 更多