有时候要对树进行过滤
// 把空的父节点删除掉
const deleteEmpty = (treeData) => {
const tree = treeData.filter((item) => {
// 判断是否是空的父节点
const isEmpty = !item.isLeaf && (!item.children || (item.children && !item.children.length));
if (item.children && item.children.length) {
item.children = deleteEmpty(item.children);
}
return !isEmpty;
});
return tree;
};
const newlist = deleteEmpty(_list);
使用antd-table时要做树形默认展开
https://www.cnblogs.com/steamed-twisted-roll/p/12997220.html
这是上面博客中原来的方法:
const newExpandedKeys = []
const render = (treeDatas) => { // 获取到所有可展开的父节点
treeDatas.map(item => {
if (item.children) {
newExpandedKeys.push(item.key)
render(item.children)
}
})
return newExpandedKeys
}
setDefaultExpanded(render(data))
然后在项目中有做扩展(加了深度的功能):
1.计算深度。返回这棵树的最大深度。
2.使得树展开到指定层级
/**
* 分级菜单相关API
*/
/** 1.按指定层级展开 */
expandLevel(expandedLevel = 0, dataSource) {
// 首先需要判断是否配置了setExpandedRowKeys属性
if (!this.setExpandedRowKeys) return null;
/**
* 尤其注意:
* 使用expandedRowKeys属性控制table的展开时,一定要和onExpand配合使用
*/
let depth = 0;
const newExpandedKeys = [];
const expand = (treeData, currentLevel) => {
// 根据expandedLevel来控制最大"展开层级"。为0代表"全部展开"
if (currentLevel >= expandedLevel && expandedLevel) {
return newExpandedKeys;
}
if (expandedLevel === 0) {
// 初始"全部展开"时计算"最大层级"
// console.log('计算最大层级');
// console.log(currentLevel);
// console.log(depth);
depth = Math.max(depth, currentLevel);
}
// 递归遍历
treeData.map((item) => {
const key = this.rowKey || 'id';
newExpandedKeys.push(item[key]);
// 但是要考虑到空分类的情况
if (item.children || (!item.children && !item.isLeaf)) {
expand(item.children || [], currentLevel + 1);
}
});
return newExpandedKeys;
};
// console.log('递归前dataSource');
// console.log(dataSource);
this.setExpandedRowKeys(expand(dataSource, 1));
// console.log('递归完成');
// console.log(newExpandedKeys);
// console.log('递归完成depth');
// console.log(depth);
if (expandedLevel === 0) {
return depth;
}
}
将list数组转成tree
// 接口数据转换
/**
*
* @param {*} param0
*/
const list2Tree = ({
list,
pKey,
key,
isLeaf
}) => {
const tree = []
for (var i = 0; i < list.length; i++) {
if (typeof isLeaf === 'function' && typeof list[i].isLeaf === 'undefined') {
list[i].isLeaf = isLeaf(list[i])
}
for (var j = 0; j < list.length; j++) {
// 如果有父节点
if (list[i][pKey] === list[j][key]) {
// 放进它父节点的children数组中;如果children不存在,初始化为空数组
list[j].children = list[j].children || []
list[j].children.push(list[i])
/** 应该在这里加,当某个节点有children的时候,一定是父结点 */
list[j].isLeaf=false
// if (!isLeaf) {
// list[j].isLeaf = false
// }
// 因为每个节点至多有一个父节点,所以这里可以退出本次循环,避免无意义的运算
break
} else {
// if (!isLeaf) {
// list[j].isLeaf = true
// }
}
}
// 如果j的值等于list的长度,说明在内层循环中没有触发break,也就是说这个节点是根节点
if (j === list.length) {
tree.push(list[i])
}
}
return tree
}