javascript - 未处理的拒绝(TypeError):无法读取未定义的属性(读取“长度”)
问题描述
为什么 children.length 导致Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'length')特别是因为 children.length 的值已成功显示在控制台上?
const getParentId = (childId) => {
var queue = [ds]
while(queue.length > 0){
const children = queue[0].children
queue.push(children)
console.log("children.length = "+children.length)
for (let i = 0; i < children.length; i++){
if (children[i].id === childId) {return queue[0].id}
}
queue.shift()
}
}
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))
};
解决方案
在一个条目没有属性while
之后循环继续循环- 代码实际上推送到. 当它报告下一行的长度时,它会抛出导致 promise 被拒绝的错误。queue
children
undefined
queue
undefined
如果我错了,请纠正我,但是说没有children
数组有children
属性是不是真的,因为只有child
节点才有children
属性?如果确实如此,则错误发生在while
循环的第二次迭代中。
我建议审查设计,getParentId
因为它似乎正在尝试从ds
节点开始的最年长的孩子的分支行走 - 并且可能应该对所有子分支进行树行走。
推荐阅读
- python-3.x - 在 Archer 中添加 AttachmentWrapper 的 POST 请求
- c# - GridView 和 DataGrid 列 DataSource 额外列
- python - 基于元组更新python字典
- jquery - 在 laravel 中按复选框过滤产品
- docker - Docker 清理 Kubernetes Pod 日志过快
- excel - 引入 [start_num] 时,带有“OR”语句的 Excel FIND 公式不起作用
- angular - TypeError:无法分配给对象'#的只读属性'plugins'
' - python - 通过循环从基于其他列的列中添加值
- reactjs - react-intl 与 react-testing-library 给出了无效的钩子调用错误
- java - 我可以使用@RepeatedTest 注释JUnit5 获得变量值吗