简体   繁体   English

当数据包含 null 值时,如何按长度对 Antd 表数据进行排序

[英]How can sort Antd table data by length, when the data contain a null value

I want to sort a table by the length of the data.我想按数据长度对表格进行排序。 But there are some null values coming.但是有一些 null 值即将到来。 This is my sorter function这是我的分拣机 function

 sorter: (a, b) => a.rechargeType.length - b.rechargeType.length

following error coming when there is a null value出现 null 值时出现以下错误

TypeError: Cannot read property 'length' of null

You can simply do that,你可以简单地这样做,

sorter: (a, b) => {
    if(a && a.rechargeType && a.rechargeType.length && b && b.rechargeType && b.rechargeType.length) {
        return a.rechargeType.length - b.rechargeType.length;
    } else if(a && a.rechargeType && a.rechargeType.length) {
        // That means be has null rechargeType, so a will come first.
        return -1;
    } else if(b && b.rechargeType && b.rechargeType.length) {
        // That means a has null rechargeType so b will come first.
        return 1;
    }

    // Both rechargeType has null value so there will be no order change.
    return 0;
}

This way null values will come last.这样 null 值将排在最后。 For more reading about the return value of sort compare function you can read this .有关排序比较 function 的返回值的更多信息,您可以阅读内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM