我開始學習 React 并且不明白,為什么它會這樣作業?我希望得到元素name:'Node2',但我得到父母name:'Node1'。我有一棵樹
jsonNodes: [{
id: 1,
name: 'Node1',
nodes: [
{
id: 2,
name: 'Node2',
nodes: [
{
id: 5,
name: 'Node5',
nodes: null,
}],
}, {
id: 4,
name: 'Node4',
nodes: null,
}],
},
{
id: 3,
name: 'Node3',
nodes: null,
}]
和一些遞回方法
getSelectedNode(nodes) {
return nodes.find(element => {
if (element.name == this.state.selectedItem)
{
return element;
}
else if (element.nodes != null)
{
return this.getSelectedNode(element.nodes);
}
else
{
return null;
}
});
}
我的錯誤是什么?
uj5u.com熱心網友回復:
您沒有正確使用 find 。如果您在其回呼中回傳任何真實的內容,它將回傳當前元素。
this.getSelectedNode(element.nodes)最終將回傳正確的元素,但它將被視為真實值,這意味著無論您做什么,如果第一個元素的任何后代匹配,則將回傳第一個元素。
你想要做的是這樣的:
getSelectedNode(nodes) {
// Use a for loop instead of forEach to avoid nested functions
// Otherwise "return" will not work properly
for (const element of nodes) {
// Check if this element is the seleted one, return it if it is
if(element.name === this.state.selectedItem) {
return element
}
// If it's not - recursively check its descendants, if it has any
if(element.nodes){
const found = this.getSelectedNode(element.nodes)
if(found){
return found
}
}
}
// didn't find anything, return null
return null
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493393.html
標籤:javascript 反应
下一篇:熊貓Sum()問題
