簡體   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