【问题标题】:React | localeCompare sort with null values反应 |使用空值进行 localeCompare 排序
【发布时间】:2018-04-25 09:24:47
【问题描述】:

我正在使用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

我在Code sand box上有完整的代码

【问题讨论】:

    标签: javascript reactjs sorting antd


    【解决方案1】:

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

    【讨论】:

    • 谢谢@N。贾达夫。你拯救了我的一天:)
    【解决方案2】:

    如果你有 ES2020,有optional chaining 可以通过返回 undefined 而不是在评估值为 null 时抛出错误来防止错误。你可以这样使用它

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

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

    【讨论】:

    • 感谢这工作。 const orderedPosts = posts.slice().sort((a, b) => b.date?.localeCompare(a.date)) 我在排序日期时遇到了同样的错误。但你的建议奏效了。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2021-11-25
    • 2022-12-29
    • 2014-09-23
    相关资源
    最近更新 更多