[英]How to move recursively inside a tree
我正在尝试创建一个树组件。 但我不知道如何在树内递归移动项目。
每个项目都是动态创建的,我想在每个级别中删除树的一个项目/分支。 树是具有拖放功能的垂直列表。 每个项目都可以有孩子。
问题是,例如,我想将 id 为 4 的项目移动到其他 position (例如 0 到 1 之间)......不会落在那个 position 上。 或者我在 3 到 5 之间移动相同的项目,放在项目之后
我不知道我做错了什么。 我想使用递归方法。
export const updateBranchsInSameLevel = (
branchs: Array<IBranch>,
fromBranch: IBranch,
toBranch: IBranch
): Array<IBranch> => {
let copyBranch: Array<IBranch> = [...branchs];
copyBranch.splice(fromBranch.position, 1);
const position: number = toBranch.position;
copyBranch.splice(position, 0, fromBranch);
return updatePostitionsAtFirstLevel(copyBranch);
};
如您所见,我正在使用拖放,这就是从分支中删除的原因。 fromBranch 是一个想要移动的分支和我想要放置的分支。
const data = [{
"id": 0,
"parentId": null,
"level": 0,
"title": "New Branch 0",
"children": [],
"position": 0
}, {
"id": 1,
"parentId": null,
"level": 0,
"title": "New Branch 1",
"children": [],
"position": 1
}, {
"id": 2,
"parentId": null,
"level": 0,
"title": "New Branch 2",
"children": [],
"position": 2
}, {
"id": 3,
"parentId": null,
"level": 0,
"title": "New Branch 3",
"children": [],
"position": 3
}, {
"id": 4,
"parentId": null,
"level": 0,
"title": "New Branch 4",
"children": [{
"id": 6,
"parentId": 4,
"level": 1,
"title": "New Branch 6",
"children": [],
"position": 0
}],
"position": 4
}, {
"id": 5,
"parentId": null,
"level": 0,
"title": "New Branch 5",
"children": [],
"position": 5
}]
我用这种递归方法解决了,它可以工作,但也许其他人有更好的解决方案。
const moveBranchToBranch = (branchs: Array<IBranch>, toBranch: IBranch, updatedBranch: IBranch): Array<IBranch> => {
const dmaExtractor = (children: Array<IBranch>) => {
children.forEach((child: IBranch, index: number) => {
if (child.id === toBranch.id) {
branchs = [...children.slice(0, index + 1), updatedBranch, ...children.slice(index + 1 )];
}
if (child.children && child.children.length > 0) {
dmaExtractor(child.children);
}
});
};
if (branchs.length) {
dmaExtractor(branchs);
}
return branchs;
}
export const updateBranchsInSameLevel = (
branchs: Array<IBranch>,
fromBranch: IBranch,
toBranch: IBranch
): Array<IBranch> => {
let copyBranch: Array<IBranch> = [...branchs];
copyBranch.splice(fromBranch.position, 1);
let updatedBranch: IBranch = Object.assign({}, fromBranch, {
level: toBranch.level,
position: toBranch.position,
parentId: toBranch.parentId
});
let updated: Array<IBranch> = moveBranchToBranch(copyBranch, toBranch, updatedBranch);
return updatePostitionsAtFirstLevel(updated);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.