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

Antd Table切换分页时selectedRowKeys返回undefined问题求助

解决Ant Design Table分页时选中状态丢失问题

问题场景与现象

在模态框中使用Ant Design Table组件并开启复选框选择功能,需求是从状态加载已勾选行作为默认选中项,并实现勾选值的持久化。当前通过useEffect填充默认选中ID后,初始页面能正确选中对应行,但切换分页时selectedRowKeys变为undefined,无法跨页保留已选中的值。

原代码

const rowSelection = {
  selections: [
    Table.SELECTION_NONE,  
  ],
  getCheckboxProps: (record) => ({
    id: record.id,
  }),
};

const columns = [
    {
      title: "Document ID",
      dataIndex: "id",
      key: "id",
      defaultSortOrder: "descend",
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: "Subject",
      dataIndex: "subject",
      key: "subject",
      width: "25%",
      sorter: (a, b) => a.subject.length - b.subject.length,
      sortDirections: ["descend", "ascend"],
    },
    {
      title: "Title",
      dataIndex: "title",
      key: "title",
      width: "25%",
      sorter: (a, b) => a.title.length - b.title.length,
      sortDirections: ["descend", "ascend"],
    },
    {
      title: "Document Type",
      dataIndex: "doc_type",
      key: "doc_type",
      render: (text, record) =>
        record.doc_type && record.doc_type.name ? record.doc_type.name : null,
    },
    {
      title: "File Type",
      dataIndex: "file_type",
      key: "file_type",
      render: (text, record) =>
        record.file_type && record.file_type.name
          ? record.file_type.name
          : null,
    },
    {
      title: "Public",
      dataIndex: "is_public",
      key: "is_public",
      align: "center",
      render: (text, record) =>
        record.ispublic ? (
          <CheckCircleFilled style={{ color: "#28a745" }} />
        ) : (
          <CloseCircleFilled style={{ color: "#dc3545" }} />
        ),
    },
    {
      title: "Date Created",
      dataIndex: "created_at",
      key: "created_at",
      render: (text, record) => dateFormatter(new Date(record.created_at)),
    },
  ];

const dateFormatter = (date) => {
  const dd = (date.getDate() < 10 ? "0" : "") + date.getDate();
  const MM = (date.getMonth() + 1 < 10 ? "0" : "") + (date.getMonth() + 1);
  const yyyy = date.getFullYear();
  return MM + "/" + dd + "/" + yyyy;
};

const [selectAlready, setSelectAlready] = useState([]);

useEffect(() => {
  if(attachmentLists && attachmentLists.length != 0) {
    const documentIds = map(attachmentLists,'id');
    if(documentIds.length != 0) {
      setAlreadySelectedRows(documentIds);        
    }      
  }
}, [attachmentLists])

<Table
  rowKey={(record) => record.id}
  rowSelection={{
    type: "checkbox",
    selectedRowKeys: selectAlready,
    onChange: (keys, selectedRowKeys, selectedRows) => {
      setSelectAlready(keys);
      setSelectedDocuments(selectedRowKeys);
    },
    preserveSelectedRowKeys: true,
    ...rowSelection,
  }}
  columns={columns}
  dataSource={data}
  pagination={{
    pageSize: 10,
    showSizeChanger: false,
    total: pageTotalSize,
    position: ["bottomLeft"],
  }}
  loading={loading}
  onChange={(pagination, filters, sorter) => handleTableChange(pagination)}
/>;

问题分析与修复方案

1. 修正状态变量名称错误

原useEffect中调用的setAlreadySelectedRows是未定义的状态 setter,应该改为setSelectAlready,否则初始默认选中状态无法正确设置。

2. 修正onChange参数错误

Ant Design Table的rowSelection.onChange回调参数为(selectedRowKeys, selectedRows),原代码错误地添加了第三个参数,导致selectedRowKeys变量获取到undefined,进而错误更新状态。

3. 统一选中状态管理

selectedRowKeys绑定的是selectAlready状态,只需维护该状态即可,无需额外冗余状态(若setSelectedDocuments是业务需要,则同步传入正确的selectedRowKeys)。

4. 确保preserveSelectedRowKeys生效

该属性依赖selectedRowKeys始终持有所有已选中ID的数组,只要状态正确维护,切换分页时Table会自动保留跨页选中状态。

修正后的关键代码

修正后的useEffect

const [selectAlready, setSelectAlready] = useState([]);

useEffect(() => {
  // 使用可选链简化判断
  if(attachmentLists?.length) {
    const documentIds = map(attachmentLists,'id');
    setSelectAlready(documentIds);        
  }      
}, [attachmentLists])

修正后的Table rowSelection配置

rowSelection={{
  type: "checkbox",
  selectedRowKeys: selectAlready,
  onChange: (selectedRowKeys, selectedRows) => {
    setSelectAlready(selectedRowKeys);
    // 若需同步到其他业务状态,传入正确的selectedRowKeys
    // setSelectedDocuments(selectedRowKeys);
  },
  preserveSelectedRowKeys: true,
  ...rowSelection,
}}

内容的提问来源于stack exchange,提问作者Jc John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:10:42