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

问题描述

我想按数据长度对表格进行排序。但是有一些空值来了。 这是我的排序功能

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

出现空值时出现以下错误

TypeError: Cannot read property 'length' of null

解决方法

你可以这样做,

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

这样 null 值会最后出现。有关排序比较函数返回值的更多信息,您可以阅读 this