反应 | localeCompare 对空值进行排序

React | localeCompare sort with null values

我正在使用 React ant design table。 在 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

我有 Code sand box

的完整代码

您可以检查您的值是否为 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