This is the 9th day of my participation in the August More Text Challenge

When we use ant Design’s UI library, we will need to use the tree control requirements, so we need to load the corresponding tree data, the following describes the asynchronous data loading method.

1. First, you need to define in state a data source treeData that loads asynchronously on click load and initialize it to an empty array.

state = {
    treeData: [],
  }
Copy the code

Add a loadData attribute to the Tree component in the render return, and assign the this.onLoadData method.

render() {
    return (
      <Tree loadData={this.onLoadData}>
        
      </Tree>
    );
  }
Copy the code

Then we define the onLoadData method, which is the unit tree click on the parent node asynchronously load the data of the child unit, the number of nodes with the parameter treeNode passed in, and structure the data of the tree from the data source unitTreeData in ROPS. const { dispatch, unitTree: { unitTreeData } } = this.props; Then send an action request that iterates through the unitTreeData and assigns its value attribute to the key so that the key equals the value; SetState ({treeData: unitTreeData}); this.setState({treeData: unitTreeData});

OnLoadData = (treeNode) => {// Data source unitTreeData const {dispatch, unitTree: { unitTreeData } } = this.props; / / the backend interface parameters passed const params = {/ / click on the node Id parentId: treeNode. Props. The dataRef. Value}; ForEach (item => {item.key = unitTreeData.foreach (item => {item.key =) item.value}); return new Promise((resolve) => { if (treeNode.props.children) { resolve(); return; } // unitTree is the namespace, fetch is the effect method dispatch({type: 'unitTree/fetch', payload: params, // callback function to prevent data synchronization of the request callback: () => { const { unitTree: { unitTreeData } } = this.props; treeNode.props.dataRef.children = unitTreeData; // treeData is the data source this.setState({treeData: unitTreeData}); }}); resolve() }); };Copy the code

3. It’s time to deal with the data source, call renderTreeNodes, map the data, and recurse based on the presence or absence of a parent node.

RenderTreeNodes = (data) => {return data.map((item) => {if (item.children) {return (<TreeNode title={item.title} key={item.key} dataRef={item}> {this.renderTreeNodes(item.children)} </TreeNode> ); } return <TreeNode {... item} dataRef={item} />; }); }Copy the code

The method is finally called in Render

Render () {return (<Tree loadData={this.onloadData}> {this.rendertreenodes (unitData)} </Tree>); }Copy the code