【问题标题】:Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'length')未处理的拒绝(TypeError):无法读取未定义的属性(读取“长度”)
【发布时间】:2021-11-19 05:36:07
【问题描述】:

为什么 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))
  };

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢您的回答!真正的问题在于你提出的问题。 queue.push(children) 应该类似于 children.forEach(child =&gt; queue.push(child)) 在英语中,我将下一个队列项设置为列表而不是实际节点。另外,我的 getParentId 设计似乎等同于这个答案stackoverflow.com/a/1616365/17011629
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2022-06-19
    • 2019-07-19
    相关资源
    最近更新 更多