React类组件中AntD表格过滤报错及失效问题求助
AntD表格过滤问题修复方案
问题1:触发过滤时抛出Uncaught TypeError: Cannot read properties of undefined (reading 'includes')
- 根因:Votes列的
voteCount是数值类型,数值没有includes方法;同时未处理voteCount为undefined的边界情况。 - 修复方式:
- 数值类型过滤可根据需求选择:若需模糊匹配则转字符串后用
includes,精确匹配直接用相等判断 - 用可选链
?.避免voteCount为undefined时的报错
- 数值类型过滤可根据需求选择:若需模糊匹配则转字符串后用
问题2:Idea列选中过滤器后所有数据消失
- 根因:
- Idea列的过滤选项未正确配置在
filters字段下,语法结构错误 onFilter逻辑错误:includes返回布尔值,与0比较结果恒为false,导致所有数据被过滤
- Idea列的过滤选项未正确配置在
- 修复方式:
- 将过滤选项数组包裹在
filters字段中 - 修正
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
相关产品推荐
相关产品推荐

