ant-design/components/tree/demo/dynamic.md

78 lines
1.6 KiB
Markdown
Raw Normal View History

2016-03-31 09:40:55 +08:00
---
order: 3
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.
```tsx
2020-01-22 12:11:49 +08:00
import React, { useState } from 'react';
import { Tree } from 'antd';
2018-06-27 15:55:04 +08:00
interface DataNode {
title: string;
key: string;
isLeaf?: boolean;
children?: DataNode[];
}
const initTreeDate: DataNode[] = [
{ title: 'Expand to load', key: '0' },
{ title: 'Expand to load', key: '1' },
{ title: 'Tree Node', key: '2', isLeaf: true },
];
// It's just a simple demo. You can use tree map to optimize update perf.
function updateTreeData(list: DataNode[], key: React.Key, children: DataNode[]): DataNode[] {
return list.map(node => {
if (node.key === key) {
return {
...node,
children,
};
} else if (node.children) {
return {
...node,
children: updateTreeData(node.children, key, children),
};
}
return node;
});
}
const Demo: React.FC<{}> = () => {
2020-01-22 12:11:49 +08:00
const [treeData, setTreeData] = useState(initTreeDate);
function onLoadData({ key, children }: any) {
return new Promise<void>(resolve => {
if (children) {
resolve();
return;
}
setTimeout(() => {
setTreeData(origin =>
updateTreeData(origin, key, [
{ title: 'Child Node', key: `${key}-0` },
{ title: 'Child Node', key: `${key}-1` },
]),
);
resolve();
}, 1000);
});
}
return <Tree loadData={onLoadData} treeData={treeData} />;
};
2016-01-07 19:05:55 +08:00
ReactDOM.render(<Demo />, mountNode);
2019-05-07 14:57:32 +08:00
```