[英]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.