reactjs - 反应表没有正确排序数字
问题描述
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,
},
解决方案
正如其他答案中所建议的那样,问题是toFixed
返回一个字符串,因此排序将使用字符串比较来完成。但是,在这种情况下强制返回数字将不起作用,因为这样您将丢失尾随0
s,我猜您仍然需要。
另一种解决方案是使用自定义排序:
accessor: d => Number(d.Invoice_Weight).toFixed(2),
sortMethod: (a, b) => Number(a)-Number(b)
您可能想要改进sortMethod
以处理 NaN 和 Infinities(如果有的话),但这是一般的想法
您可以使用它来强制字符串返回一个数字,但只能在排序的上下文中,而不影响显示的值
推荐阅读
- c# - 在 MongoDB 中过滤
- apache-spark - Apache Spark 2.4.0、AWS EMR、Spark Redshift 和用户类抛出异常:java.lang.AbstractMethodError
- javascript - Strapi:GraphQL ctx.state.user 未定义内部策略
- google-chrome - 谷歌应用程序脚本导航到谷歌表的给定行
- java - java jaxb unmarshal with jenkins Feed Object
- angular - Angular:在获取中有条件地设置“凭据”选项
- linux - 在哪里可以找到最近的文件以及如何管理它们?
- postgresql - 聚合计数直到每个 ISO WEEK
- html - HTML 复选框样式
- spring - 处理异常的更好方法是 spring-boot