简体   繁体   English

反应 | localeCompare 排序与空值

[英]React | localeCompare sort with null values

I'm using React ant design table .我正在使用React ant design table In that table I'm trying to sort with null values by using localeCompare It shows Type error.在该表中,我尝试使用localeCompare对空值进行排序,它显示类型错误。

JSON JSON

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

When I sort I'm getting error like:当我排序时,我收到如下错误:

 TypeError: Cannot read property 'localeCompare' of null

I have full code on Code sand box我在代码沙盒上有完整的代码

You can check if your value is null then you can assign blank using pipe.您可以检查您的值是否为null然后您可以使用管道分配空白。

In your code you can do like this在您的代码中,您可以这样做

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

DEMO演示

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

if you have ES2020, there is optional chaining to prevent error by returning undefined instead of throwing error when evaluated value is nullish.如果你有 ES2020,有一个optional chaining来防止错误,当评估值为空时返回 undefined 而不是抛出错误。 You can use it like this你可以像这样使用它

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

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining来源: 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