首页 > 解决方案 > 未处理的拒绝(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))
  };

标签: javascriptreactjs

解决方案


在一个条目没有属性while之后循环继续循环- 代码实际上推送到. 当它报告下一行的长度时,它会抛出导致 promise 被拒绝的错误。queuechildrenundefinedqueueundefined

如果我错了,请纠正我,但是说没有children数组有children属性是不是真的,因为只有child节点才有children属性?如果确实如此,则错误发生在while循环的第二次迭代中。

我建议审查设计,getParentId因为它似乎正在尝试从ds节点开始的最年长的孩子的分支行走 - 并且可能应该对所有子分支进行树行走。


推荐阅读