【问题标题】:React-Native - recursing through nested object crashingReact-Native - 通过嵌套对象崩溃递归
【发布时间】:2018-02-02 00:04:15
【问题描述】:

我在一个普通的 CRNA 项目中实现了从 (Iterate through Nested JavaScript Objects) 获取的以下函数:

var findObjectByLabel = function(obj, label) { if(obj.label === label) { return obj; } for(var i in obj) { if(obj.hasOwnProperty(i)){ var foundLabel = findObjectByLabel(obj[i], label); if(foundLabel) { return foundLabel; } } } return null; };

当我尝试在构造函数或任何生命周期方法中执行此代码时,应用程序因超出最大调用堆栈大小而崩溃。这在 RN 中是不允许的吗?我是否必须将其转换为迭代版本?

【问题讨论】:

    标签: javascript reactjs typescript recursion react-native


    【解决方案1】:

    如果您为上述功能考虑以下场景,您可以了解它为什么会中断:

    type Node = { link: Node; value: number; };
    const x: Node = { link: null, value: 0 };
    const y: Node = { link: x, value: 1 };
    x.link = y;
    
    findObjectByLabel(x, 'foo');
    

    因为存在循环引用,所以您的递归将无限进行,您将达到最大调用堆栈大小。

    您的对象结构中可能存在某种循环引用,导致您遇到此问题。

    如果您可以保证所有命中对象都将具有非空 label 并且标签是唯一的,那么您可以跟踪 seenLabels 而不会递归到您已经看到标签的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 2012-02-12
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多