2016-03-31 09:40:55 +08:00
|
|
|
---
|
|
|
|
order: 3
|
2017-02-19 21:23:38 +08:00
|
|
|
title:
|
2016-07-21 09:52:39 +08:00
|
|
|
zh-CN: 异步数据加载
|
|
|
|
en-US: load data asynchronously
|
2016-03-31 09:40:55 +08:00
|
|
|
---
|
2015-10-27 15:47:01 +08:00
|
|
|
|
2016-07-21 09:52:39 +08:00
|
|
|
## zh-CN
|
|
|
|
|
2016-01-28 15:13:17 +08:00
|
|
|
点击展开节点,动态加载数据。
|
2015-10-27 15:47:01 +08:00
|
|
|
|
2016-07-21 09:52:39 +08:00
|
|
|
## en-US
|
|
|
|
|
|
|
|
To load data asynchronously when click to expand a treeNode.
|
|
|
|
|
2019-08-12 13:22:36 +08:00
|
|
|
```tsx
|
2015-10-29 13:42:40 +08:00
|
|
|
import { Tree } from 'antd';
|
2022-05-23 14:37:16 +08:00
|
|
|
import React, { useState } from 'react';
|
2018-06-27 15:55:04 +08:00
|
|
|
|
2020-03-08 00:19:05 +08:00
|
|
|
interface DataNode {
|
|
|
|
title: string;
|
|
|
|
key: string;
|
|
|
|
isLeaf?: boolean;
|
|
|
|
children?: DataNode[];
|
|
|
|
}
|
|
|
|
|
2021-03-26 10:44:54 +08:00
|
|
|
const initTreeData: DataNode[] = [
|
2019-08-12 13:22:36 +08:00
|
|
|
{ title: 'Expand to load', key: '0' },
|
|
|
|
{ title: 'Expand to load', key: '1' },
|
|
|
|
{ title: 'Tree Node', key: '2', isLeaf: true },
|
|
|
|
];
|
|
|
|
|
2020-03-08 00:19:05 +08:00
|
|
|
// It's just a simple demo. You can use tree map to optimize update perf.
|
2022-05-19 09:46:26 +08:00
|
|
|
const updateTreeData = (list: DataNode[], key: React.Key, children: DataNode[]): DataNode[] =>
|
|
|
|
list.map(node => {
|
2020-03-08 00:19:05 +08:00
|
|
|
if (node.key === key) {
|
|
|
|
return {
|
|
|
|
...node,
|
|
|
|
children,
|
|
|
|
};
|
2021-02-23 10:45:11 +08:00
|
|
|
}
|
|
|
|
if (node.children) {
|
2020-03-08 00:19:05 +08:00
|
|
|
return {
|
|
|
|
...node,
|
|
|
|
children: updateTreeData(node.children, key, children),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return node;
|
|
|
|
});
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const App: React.FC = () => {
|
2021-03-26 10:44:54 +08:00
|
|
|
const [treeData, setTreeData] = useState(initTreeData);
|
2019-08-12 13:22:36 +08:00
|
|
|
|
2021-08-30 13:04:21 +08:00
|
|
|
const onLoadData = ({ key, children }: any) =>
|
|
|
|
new Promise<void>(resolve => {
|
2020-03-08 00:19:05 +08:00
|
|
|
if (children) {
|
2019-08-12 13:22:36 +08:00
|
|
|
resolve();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
setTimeout(() => {
|
2020-03-08 00:19:05 +08:00
|
|
|
setTreeData(origin =>
|
|
|
|
updateTreeData(origin, key, [
|
|
|
|
{ title: 'Child Node', key: `${key}-0` },
|
|
|
|
{ title: 'Child Node', key: `${key}-1` },
|
|
|
|
]),
|
|
|
|
);
|
|
|
|
|
2019-08-12 13:22:36 +08:00
|
|
|
resolve();
|
|
|
|
}, 1000);
|
|
|
|
});
|
|
|
|
|
|
|
|
return <Tree loadData={onLoadData} treeData={treeData} />;
|
|
|
|
};
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
export default App;
|
2019-05-07 14:57:32 +08:00
|
|
|
```
|