Tree Component Data Processing

效果

AntTree-20191024.gif

后端接口返回数据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) => {
// 第一次遍历给省份数据加入key
let i = {};
let PIndex = index++; // PIndex用于作最外层的key
if (item["city"].length > 1) {
// 不是直辖市对应city就有多个
i["title"] = item.province.name;
i["key"] = PIndex;
i["children"] = [];
OriginResult[PIndex].city.forEach((ii, IN) => {
// 遍历当前索引下后端数据的city数据
let CIndex = IN++;
i["children"].push({
// 插入children数据
title: ii.name,
key: PIndex + "-" + CIndex // 通过0-0作为key,方便后面判断城市和省份的所属关系
});
});
navs.push(i);
} else {
// 直辖市对应city就只有一个,为了满足后端接口入参需求
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": "福安" }]

Tree Component Data Processing
https://www.pengsifan.com/2019/10/24/TreeComponentAlgorithm/
作者
Van
发布于
2019年10月24日
许可协议