繁体   English   中英

反应 | localeCompare 排序与空值

[英]React | localeCompare sort with null values

我正在使用React ant design table 在该表中,我尝试使用localeCompare对空值进行排序,它显示类型错误。

JSON

const data = [{
  key: '1',
  name: null,
  age: 32,
}, {
  key: '2',
  name: 'Jim Green',
  age: '32',
}, {
  key: '3',
  name: 'Joe Black',
  age: 32,
}];

当我排序时,我收到如下错误:

 TypeError: Cannot read property 'localeCompare' of null

我在代码沙盒上有完整的代码

您可以检查您的值是否为null然后您可以使用管道分配空白。

在您的代码中,您可以这样做

{
    title: "Name",
    dataIndex: "name",
    key: "name",
    sorter: (a, b) => {
        a = a.name || '';
        b = b.name || '';
        return a.localeCompare(b);
    }
},

演示

 const data = [{ key: '1', name: null, age: 32, }, { key: '2', name: 'Jim Green', age: '32', }, { key: '3', name: 'Joe Black', age: 32, }]; console.log(data.sort((a,b)=>{ a= a.name||''; b= b.name||''; return a.localeCompare(b) }));
 .as-console-wrapper { max-height: 100% !important; top: 0;}

如果你有 ES2020,有一个optional chaining来防止错误,当评估值为空时返回 undefined 而不是抛出错误。 你可以像这样使用它

arr.sort((a,b) => a?.localeCompare(b))

来源: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

暂无
暂无

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

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