为何children.length控制台打印正常却报Cannot read properties of undefined (reading 'length')错误
问题根因
你看到的children.length成功打印是第一次循环的输出,报错发生在第二轮循环,本质是getParentId的广度优先遍历队列逻辑存在问题,具体原因如下:
- 队列元素类型不一致:你初始化队列时放入的是节点对象,但第一次循环时直接把
children数组本身推入了队列。第一轮循环结束执行queue.shift()后,队列里剩下的元素就是刚才推入的children数组,第二轮循环取queue[0]拿到的是数组而非节点对象,数组没有children属性,此时const children = queue[0].children拿到的就是undefined,读取undefined.length就触发了类型错误。 - 缺少边界兼容:哪怕队列逻辑修正后,也存在部分节点没有
children属性的可能,直接读取length也会触发同类型错误,需要加默认值兼容。
修正后的代码
const getParentId = (childId) => { var queue = [ds] while(queue.length > 0){ const currentNode = queue[0] // 兼容没有children的节点,默认赋值为空数组 const children = currentNode.children ?? [] console.log("children.length = "+children.length) for (let i = 0; i < children.length; i++){ if (children[i].id === childId) {return currentNode.id} // 把子节点推入队列,而不是把整个children数组推入 queue.push(children[i]) } queue.shift() } // 没找到的情况返回兜底值,避免上层调用报错 return null } const addSiblingNodes = async () => { const child = [...selectedNodes][0] const childId = child.id const newNodes = getNewNodes() await dsDigger.addSiblings(childId, newNodes); setDS({ ...dsDigger.ds }); console.log("the parent of "+childId +" is "+ getParentId(childId)) };
内容的提问来源于stack exchange,提问作者Nbot07
相关产品推荐
相关产品推荐

