2015-10-27 15:47:01 +08:00
|
|
|
# 异步数据加载
|
|
|
|
|
|
|
|
- order: 3
|
|
|
|
|
|
|
|
异步加载数据
|
|
|
|
|
|
|
|
---
|
|
|
|
|
|
|
|
````jsx
|
2015-10-29 13:42:40 +08:00
|
|
|
import { Tree } from 'antd';
|
|
|
|
const TreeNode = Tree.TreeNode;
|
2015-10-27 15:47:01 +08:00
|
|
|
|
|
|
|
const asyncTree = [
|
|
|
|
{name: "pNode 01", key: "0-0"},
|
|
|
|
];
|
|
|
|
|
2015-10-29 09:55:47 +08:00
|
|
|
const generateTreeNodes = () => {
|
|
|
|
const arr = [
|
2015-10-27 15:47:01 +08:00
|
|
|
{name: "伯约", key: "0-0-0"},
|
2015-10-29 09:55:47 +08:00
|
|
|
];
|
2015-10-27 15:47:01 +08:00
|
|
|
return arr;
|
|
|
|
}
|
|
|
|
|
|
|
|
const TreeDemo = React.createClass({
|
|
|
|
timeout(duration = 0) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
setTimeout(resolve.bind(this), duration);
|
|
|
|
})
|
|
|
|
},
|
|
|
|
getInitialState() {
|
|
|
|
return {
|
|
|
|
treeData: []
|
|
|
|
};
|
|
|
|
},
|
|
|
|
componentDidMount() {
|
|
|
|
this.timeout(1000).then(() => {
|
|
|
|
this.setState({
|
|
|
|
treeData: asyncTree
|
|
|
|
});
|
|
|
|
return asyncTree;
|
|
|
|
});
|
|
|
|
},
|
|
|
|
handleSelect(info) {
|
|
|
|
console.log('selected', info);
|
|
|
|
},
|
|
|
|
handleDataLoaded(treeNode) {
|
|
|
|
return this.timeout(1000).then(() => {
|
2015-10-29 09:55:47 +08:00
|
|
|
const child = generateTreeNodes();
|
2015-10-27 15:47:01 +08:00
|
|
|
const treeData = [...this.state.treeData];
|
|
|
|
treeData.forEach((item) => {
|
|
|
|
if (item.key === treeNode.props.eventKey) {
|
|
|
|
item.children = child;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
this.setState({treeData});
|
|
|
|
return child;
|
|
|
|
});
|
|
|
|
},
|
|
|
|
render() {
|
|
|
|
const loop = (data) => {
|
|
|
|
return data.map((item) => {
|
|
|
|
if (item.children) {
|
|
|
|
return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>;
|
|
|
|
} else {
|
|
|
|
return <TreeNode title={item.name} key={item.key}></TreeNode>;
|
|
|
|
}
|
|
|
|
})
|
|
|
|
};
|
2015-10-29 09:55:47 +08:00
|
|
|
const parseTreeNode = data => loop(data);
|
2015-10-27 15:47:01 +08:00
|
|
|
let treeNodes = parseTreeNode(this.state.treeData);
|
|
|
|
return (
|
|
|
|
<Tree onSelect={this.handleSelect} onDataLoaded={this.handleDataLoaded} showLine={false}>
|
|
|
|
{treeNodes}
|
|
|
|
</Tree>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2015-10-27 16:44:31 +08:00
|
|
|
ReactDOM.render(<TreeDemo />, document.getElementById('components-tree-demo-dynamic'));
|
2015-10-27 15:47:01 +08:00
|
|
|
````
|