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

AntDesign可展开表格轮询更新重渲染时已展开行自动收起如何解决

问题原因

Ant Design Table 的可展开行默认是非受控模式,展开状态由组件内部维护,当 dataSource 更新触发组件重渲染时,内部的展开状态会被重置为初始值,就会出现已展开行自动收起的问题。

解决方案

将可展开行改为受控模式,手动维护展开的行key集合即可:

  1. 在组件内声明状态存储已展开的行key
import { useState } from 'react';

// 这里假设你的产品数据唯一标识字段是id,可根据你的实际字段调整
const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  1. 给Table的expandable属性添加受控配置
<Table
  sortDirections={["ascend", "descend", "ascend"]}
  pagination={false}
  columns={columns}
  dataSource={products}
  expandable={{
    expandedRowKeys: expandedRowKeys, // 绑定受控的展开key集合
    onExpand: (expanded, record) => {
      if (expanded) {
        // 行展开时把当前行key加入集合
        setExpandedRowKeys(prev => [...prev, record.id]);
      } else {
        // 行收起时把当前行key从集合移除
        setExpandedRowKeys(prev => prev.filter(key => key !== record.id));
      }
    }
  }}
/>;
可选优化

如果需要轮询更新数据后,保留之前的展开状态同时过滤掉已经被删除的行key,可以在拉取新数据的回调里添加对应逻辑:

// 拉取新产品列表成功后的处理逻辑
const fetchProductsSuccess = (newProducts) => {
  setProducts(newProducts);
  // 过滤掉已经不存在的行对应的展开key
  const newProductIds = newProducts.map(item => item.id);
  setExpandedRowKeys(prev => prev.filter(key => newProductIds.includes(key)));
}

内容的提问来源于stack exchange,提问作者Mohsin Yaqoob Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:06:00