React:如何遍历树视图结构中的所有子节点?



我正在使用反应可扩展的树视图结构来显示家谱数据。用下面的代码,我用家谱数据遍历items对象,将其存储到const data中,然后递归地传递给TreeView,就像react-expandable-treeview文档中所指示的那样:

const items = props.item;
var x = 0;
const data = [{
id: x,
label: items.first_name, // parent #1
children: items.children.map( (child, idx) => {
id: x= ++idx,
label: child.first_name, // child of parent #1
children: child.children.map( (child_child) => ({
id: x = ++idx,
label: child_child.first_name,
children: child_child.children
? child_child.children.map( (child_child_child) => ({
id: x = ++idx,
label: child_child_child.first_name,
children: child_child_child.children
}))
: null
}))
}))
}]

然而,使用上面的算法,我只能得到根节点、它的子节点和这个家族的另外两代。这是一个结构的截图,它正确地显示了节点的数量和它们之间的关系,但是它们的索引和名字没有正确显示。

我不知道如何执行最后一个映射函数,所以

id: x = ++idx,
label: the_rest_of_children.first_name,
children: the_rest_of_children.children

适用于其余子节点,并扩展所有子节点,直到最后一个节点。我如何修复我的代码以获得正确的输出?

使用递归

let index = 0
function visit(node) {
return {
label: node.first_name,
id: index++,
// pass `visit` function as an argument
children: node.children.map(visit) 
}
}
const data = visit(props.items)

递归不是遍历树状结构的唯一方法。如果你的树非常复杂,实现迭代遍历算法会更安全:

如果递归实现如此简单,为什么要用迭代实现呢?当然,是为了避免堆栈溢出。大多数运行时引擎/编译器对程序可以进行多少嵌套调用设置了限制。如果树的高度大于此限制,则程序将崩溃并出现堆栈溢出错误. ...

但这些情况在web开发中并不常见。

相关内容

最新更新