效果
后端接口返回数据OriginResult
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| "result": [ { "province": { "name": "安徽", “id”:'0-0' }, "city": [ { "name": "安庆", parentId:'0-0' }, { "name": "蚌埠" }, ] }, { "province": { "name": "重庆" }, "city": [ { "name": "重庆" } ] } ]
|
Ant 的 Tree 组件需要的数据格式如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| treeData: [ { "title": '安徽', "key": 0, "children": [ { "title": '安庆', "key": "0-0" }, { "title": '蚌埠', "key": "0-1" } ], }, { "title": '重庆', "key": "重庆" }, ];
|
后端数据转换为 Tree 组件所需数据的算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| let navs = []; if (OriginResult != undefined && OriginResult.length > 0) { OriginResult.forEach((item, index) => { let i = {}; let PIndex = index++; if (item["city"].length > 1) { i["title"] = item.province.name; i["key"] = PIndex; i["children"] = []; OriginResult[PIndex].city.forEach((ii, IN) => { let CIndex = IN++; i["children"].push({ title: ii.name, key: PIndex + "-" + CIndex }); }); navs.push(i); } else { i["title"] = item.province.name; i["key"] = item.province.name; navs.push(i); } }); this.setState( { CityTreeList: this.state.CityTreeList.concat(navs) }, () => { console.log(this.state.CityTreeList); } ); }
|
现在后端数据已经整合到了 CityTreeList 中,且符合 Ant 的 Tree 组件格式要求。但后端要求入参符合如下格式,意味着我们触发确定接口保存用户所选省份和城市时需要再次遍历勾选内容进行数据重组
1 2 3 4 5 6
| "city": [ { "province": "string", "city": "string" } ]
|
Ant 的 Tree 组件有一个 onCheck 属性,会记录用户点击的内容,平铺到 checkedKeys 数组中
1 2 3 4 5 6 7 8 9 10 11 12
| [ "澳门", "蚌埠", "巢湖", "福建", "福安", "福州", "晋江", "宁德", "泉州", "武夷山" ]
|
将勾选数据处理为后端入参形式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| onCheck = checkedKeys => { // console.log("onCheck", checkedKeys); this.setState({ checkedKeys }); let nav = []; const { CityTreeList } = this.state; checkedKeys.forEach(item => { CityTreeList.forEach(x => { if (x.key === item) { nav.push({ province: item, city: item }); } else if (x.children != undefined) { x.children.forEach(xx => { if (xx.key === item) { nav.push({ province: x.title, city: xx.title }); } }); } }); }); this.setState( { city: nav }, () => { this.props.sendCityData(this.state.city); } ); };
|
处理后的格式如下
1
| [{ "province": "澳门", "city": "澳门" }, { "province": "福建", "city": "福安" }]
|