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

React类组件中AntD表格过滤报错及失效问题求助

AntD表格过滤问题修复方案

问题1:触发过滤时抛出Uncaught TypeError: Cannot read properties of undefined (reading 'includes')

  • 根因:Votes列的voteCount是数值类型,数值没有includes方法;同时未处理voteCount为undefined的边界情况。
  • 修复方式:
    • 数值类型过滤可根据需求选择:若需模糊匹配则转字符串后用includes,精确匹配直接用相等判断
    • 用可选链?.避免voteCount为undefined时的报错

问题2:Idea列选中过滤器后所有数据消失

  • 根因:
    1. Idea列的过滤选项未正确配置在filters字段下,语法结构错误
    2. onFilter逻辑错误:includes返回布尔值,与0比较结果恒为false,导致所有数据被过滤
  • 修复方式:
    1. 将过滤选项数组包裹在filters字段中
    2. 修正onFilter逻辑,直接返回includes的布尔结果(若需精确匹配可改用===)

修正后的完整代码

render() {
  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  };

  const columns = [
    {
      title: 'Stack Rank',
      key: 'stackRank',
      dataIndex: 'rank',
      sorter: (a, b) => a.rank - b.rank,
    },
    {
      title: 'Idea',
      dataIndex: 'title',
      key: 'idea',
      sorter: (a, b) => a.title.length - b.title.length,
      // 修复:过滤选项正确配置在filters字段下
      filters: [
        {
          text: 'Mini',
          value: 'Mini',
        },
        {
          text: 'Choc Flavor',
          value: 'Choc Flavor',
        },
      ],
      // 修复:直接返回includes的布尔结果
      onFilter: (value, record) => record.title?.includes(value),
      render: (_, record) => (
        <Space size="middle">
          <Link to={`/idea-detail/${this.product_id}/${record.ideaId}`}>{record.title}</Link>
        </Space>
      ),
    },
    {
      title: 'Votes',
      dataIndex: 'voteCount',
      key: 'voteCount',
      sorter: (a, b) => a.voteCount - b.voteCount,
      // 修复:数值类型处理,支持模糊匹配或精确匹配
      onFilter: (value, record) => {
        const count = record.voteCount;
        if (count === undefined) return false;
        // 若需精确匹配用 count === Number(value),模糊匹配则转字符串
        return count.toString().includes(value);
      },
      sortDirections: ['descend', 'ascend'],
    },    
  ];

  return (
    <Table 
      columns={columns} 
      dataSource={this.state.idea_list} 
      onChange={onChange} 
      pagination={{}} 
    />
  );
}

内容的提问来源于stack exchange,提问作者Ahmed Nizami

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:06