首先,讓我解釋一下我想做什么。我有樹狀資料結構,具有任意深度,我想從中列出我作為道具傳遞給子組件的所有非葉分支的串列。資料集和遞回函式如下。
問題:我在陣列中得到雙資料!我注意到該函式getBranches()也在 chrome VM 中被呼叫,它只是將相同的資料再次附加到已經存在的陣列中。見下圖。我的方法從根本上是錯誤的嗎?該怎么辦?
const treeData = {
'first-level-node-1': { // key
label: 'Regija',
type: TYPES[1],
index: 0, // rendering order
url: 'http://opa.com',
nodes: {
'second-level-node-1': {
label: 'Bolnica BN',
index: 0,
type: 1,
nodes: {
'third-level-node-1': {
label: 'Konektor Sysmex',
index: 0,
nodes: {},
type: TYPES[0]
},
},
},
},
},
'first-level-node-2': {
label: 'Regija 2',
index: 1,
type: TYPES[1],
nodes: {
'2-1': {
label: 'Dz Trebinje',
index: 0,
type: 1,
nodes: {
'3-1': {
label: 'Konektor Biomerux',
index: 0,
hasNodes: false,
type: TYPES[0],
}
}
}
}
},
};
我的 getBranches() 功能:
const getBranches = (treeData) => {
console.log('i= ',i )
Object.keys(treeData).forEach((key) => {
if (treeData[key].type!==TYPES[0]) {
branches.push({key: key, label: treeData[key].label});
console.log({key: key, label: treeData[key].label})
treeData[key].nodes && getBranches(treeData[key].nodes)
};
});
return [...branches];
};
我的組件:
const Sites = () => {
const branches = getBranches(treeData);
console.log(branches);
//const [data, setData] = useState(treeData);
return (
<Container fluid="md">
<Row>
<Col>
<MyTreeView data={treeData}/>
</Col>
<Col>
<BranchView
sites={treeData}
parentList={branches}
/>
</Col>
</Row>
</Container>
);
};
一些附加資訊:
分支與葉子的區別在于屬性 type
圖片。注意 is

uj5u.com熱心網友回復:
我猜問題只是你沒有branches在你的函式中宣告,使它成為一個全域變數。因此,下次運行該函式時,您將附加到它。添加const宣告應該可以。
也就是說,我認為您可以getBranches以一種簡潔的方式進行簡化:
const getBranches = (o) => Object .entries (o) .flatMap (
([key, {label, type, nodes}]) => [
... (type == TYPES [0] ? [] : [{key, label}]),
... (nodes ? getBranches (nodes) : [])
]
)
const TYPES = [0, 1]
const treeData = {"first-level-node-1": {label: "Regija", type: TYPES[1], index: 0, url: "http: //opa.com", nodes: {"second-level-node-1": {label: "Bolnica BN", index: 0, type: 1, nodes: {"third-level-node-1": {label: "Konektor Sysmex", index: 0, nodes: {}, type: TYPES[0]}}}}}, "first-level-node-2": {label: "Regija 2", index: 1, type: TYPES[1], nodes: {"2-1": {label: "Dz Trebinje", index: 0, type: 1, nodes: {"3-1": {label: "Konektor Biomerux", index: 0, hasNodes: false, type: TYPES[0]}}}}}}
console .log (getBranches (treeData))
.as-console-wrapper {max-height: 100% !important; top: 0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493073.html
標籤:javascript 反应 递归
