Can't sort Column in Ant Design Table in Gatsby site

穿精又带淫゛_ 提交于 2020-01-21 09:57:26

问题


I have implement an Ant Design Table in a Gatsby site. I am pulling in the data from 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}.

So, I am stuck -- any idea why this is not working and how to fix it?

Thanks.


回答1:


@norbitrial's answer is correct, as for reference here is a generic sorter (for numbers and strings):

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
  }
]



回答2:


I guess you can use instead of a.node.title - b.node.title the String.prototype.localeCompare for proper sorting. 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.

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!



来源:https://stackoverflow.com/questions/59479703/cant-sort-column-in-ant-design-table-in-gatsby-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!