[英]Can't sort Column in Ant Design Table in Gatsby site
I have implement an Ant Design Table in a Gatsby site.我在 Gatsby 站点中实现了一个 Ant 设计表。 I am pulling in the data from graphql.我正在从 graphql 中提取数据。 So far everything has worked just fine.到目前为止,一切都运行良好。 The data is displaying properly, pagination works, etc.数据显示正常,分页工作等。
Now I want to add the ability to sort the columns.现在我想添加对列进行排序的功能。 To do so, I set up the table and columns as follows:为此,我按如下方式设置表和列:
<Table
dataSource={data.allNewsFeed.edges}
onChange={onChange}
rowSelection={rowSelection}
rowKey="id"
>
<Column
title="Title"
dataIndex="node.title"
key="title"
sorter={(a, b) => a.node.title - b.node.title}
sortDirections={["descend", "ascend"]}
/>
</Table>
Now, the icon for sorting the column does shows up, but nothing happens when I click on it.现在,用于对列进行排序的图标确实出现了,但是当我单击它时没有任何反应。
Same thing happens if I remove .node
from the sorter function: sorter={(a, b) => a.title - b.title}
.如果我从排序器函数中删除.node
也会发生同样的事情: sorter={(a, b) => a.title - b.title}
。
So, I am stuck -- any idea why this is not working and how to fix it?所以,我被卡住了 - 知道为什么这不起作用以及如何解决它吗?
Thanks.谢谢。
I guess you can use instead of a.node.title - b.node.title
the String.prototype.localeCompare
for proper sorting.我想您可以使用String.prototype.localeCompare
代替a.node.title - b.node.title
进行正确排序。 As the documentation states:正如文档所述:
The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. localeCompare() 方法返回一个数字,该数字指示引用字符串在排序顺序中是在给定字符串之前还是之后,或者是否与给定字符串相同。
Somehow this:不知怎的:
const values = ['random', 'something', 'else', 'text']; const result = values.sort((a,b) => { return a.localeCompare(b); }); console.log(result);
So I guess in the mentioned case it would be:所以我想在提到的情况下它会是:
<Column title="Title"
dataIndex="node.title"
key="title"
sorter={(a, b) => a.node.title.localeCompare(b.node.title)}
sortDirections={["descend", "ascend"]} />
I hope this helps!我希望这有帮助!
@norbitrial's answer is correct, as for reference here is a generic sorter (for numbers and strings): @norbitrial 的答案是正确的,作为参考,这里是一个通用排序器(用于数字和字符串):
const sorter = (a, b) => (isNaN(a) && isNaN(b) ? (a || '').localeCompare(b || '') : a - b);
// Usage example with antd table column
[
{
title: 'Status',
dataIndex: 'status',
key: 'status',
width: '10%',
// status can be Number or String
sorter: (a, b) => sorter(a.status, b.status),
render: Name
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.