antd table 树形数据动态加载
antd 的 table 组件支持树形结构的数据,不过前提是需要将整棵树的数据一次性全部返回,对于数据量比较大的情况下,可能会需要动态加载数据。
export default function DynamicTable() {
const [loading, setLoading] = useState(false);
const [list, setList] = useState([]);
const getList = useCallback(
async () => {
setLoading(true);
const res: any = await getTableData();
setLoading(false);
const tableData = res.data;
// 默认都有children,方便table生成展开功能
tableData?.map((item: any) => {
item.children = [];
return item;
});
setList(tableData);
},
[]
);
useEffect(() => {
getList();
}, [getList]);
const onExpand = async (expanded: boolean, record: any) => {
//expanded是否展开 record每一项的值
const id = record.id;
const pList = list;
if (!expanded) return;
if (record.children?.length > 0) return;
const data = { pid: [id] };
const res: any = await getTableData(data);
setLoading(false);
let tableData = res.data || [];
// 递归遍历查找当前项,并将children插入
const dataMap = (items: any) => {
items.find((item: any) => {
if (item.id === id) {
item.children = tableData;
return item;
}
if (item.children?.length > 0) {
dataMap(item.children);
}
});
};
dataMap(pList);
setList([...pList]);
};
return (
<Table
columns={columns}
dataSource={list}
size="middle"
loading={loading}
rowKey={(record: any) => record.id}
pagination={false}
expandIcon={({ expanded, onExpand, record }) => {
//expanded-是否可展开, onExpand-展开事件默认, record-每一项的值 设置自定义图标
if (record.level < 3) {
//第一和第二层级才有图标(根据自己的额业务需求变动)
if (expanded) {
//根据是否可以展开判断
return <MinusSquareOutlined onClick={(e) => onExpand(record, e)} />;
} else {
return <PlusSquareOutlined onClick={(e) => onExpand(record, e)} />;
}
} else {
return null;
}
}}
indentSize={30}
onExpand={onExpand}
/>
);
}