You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Ant Design表格使用localeCompare排序含null值时出现类型错误

解决Ant Design表格排序时localeCompare遇到null的类型错误

这个问题其实挺常见的——你的数据里name字段存在null值,当Ant Design表格触发排序时,默认的排序逻辑会直接对字段值调用localeCompare,但null根本没有这个方法,所以才会抛出TypeError: Cannot read property 'localeCompare' of null。

咱们只需要给name列自定义一个排序函数,提前处理null值的边界情况就能搞定,这里有两种实用的处理方式:

方式一:将null转为空字符串(简单直接)

直接把null转换成空字符串,这样就能安全调用localeCompare,空字符串会默认排在所有非空字符串的前面:

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    sorter: (a, b) => {
      // 用空值合并运算符处理null/undefined
      const nameA = a.name ?? '';
      const nameB = b.name ?? '';
      return nameA.localeCompare(nameB);
    },
  },
  // 其他列配置...
];

方式二:自定义null值的排序位置(更灵活)

如果你想明确控制null值的排序优先级(比如始终排在最前面或最后面),可以用条件判断来精准处理:

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    sorter: (a, b) => {
      // 两个都是null则排序相等
      if (a.name === null && b.name === null) return 0;
      // a是null则排在前面(返回-1),b是null则a排在后面(返回1)
      if (a.name === null) return -1;
      if (b.name === null) return 1;
      // 正常字符串排序
      return a.name.localeCompare(b.name);
    },
  },
  // 其他列配置...
];

完整示例代码

结合你的数据,完整的表格组件代码如下:

import React from 'react';
import { Table } from 'antd';

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

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    sorter: (a, b) => {
      const nameA = a.name ?? '';
      const nameB = b.name ?? '';
      return nameA.localeCompare(nameB);
    },
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
    // 顺便处理age字段混合字符串和数字的情况
    sorter: (a, b) => Number(a.age) - Number(b.age),
  },
];

const App = () => <Table columns={columns} dataSource={data} />;

export default App;

本质上,Ant Design表格的sorter属性允许我们完全自定义排序逻辑,只要提前处理好null、undefined这类特殊值,就能轻松避免类型错误啦。

内容的提问来源于stack exchange,提问作者Maria Jeysingh Anbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:20:03