【问题标题】:VM1374:32 Uncaught TypeError: Converting circular structure to JSON(…)VM1374:32 未捕获的类型错误:将循环结构转换为 JSON(…)
【发布时间】:2017-03-22 19:30:37
【问题描述】:

我是 JS 新手。我正在尝试在我的 console.log 中打印值。我收到以下错误:

VM1374:32 Uncaught TypeError: Converting circular structure to JSON(…)

我的代码如下:

console.log("this.props.children[this.state.selected]---->" + JSON.stringify(this.props.children[this.state.selected]));

【问题讨论】:

    标签: javascript jquery html json reactjs


    【解决方案1】:

    这是一个很常见的问题。抛出 Converting circular structure to JSON(...) 是因为您试图打印出一个最终通过其属性之一引用自身的对象。

    这里是JSFiddle 解决此问题的最简单方法之一:

    var a = {
      b: null
    };
    
    // Prints fine
    console.log(JSON.stringify(a, null, 3));
    
    a.b = a;
    
    // Throws an error, as a.b *is* a
    console.log(JSON.stringify(a, null, 3));
    

    当您调用JSON.stringify 时,浏览器会像一棵大树一样遍历您的对象,像分支一样沿着每个属性向下移动,并将它可以转换为字符串。 在上面的示例中,属性b 最初为空,这导致“字符串化”成功。当我们将a.b 设置为a 本身时,我们现在得到了这种树:

    a
    |-b: a
         |-b: a
              |-b: a
                   ...
    

    这种结构是循环的,因为对象引用了它自己。无法将其写为 JSON,因为它会永远持续下去,因此会引发错误。

    对于您的具体问题,这发生在 React 中,因为 React 对象引用了它们的父对象,它们引用了它们的子对象,它们引用了它们的父对象,它们引用了它们的子对象......它会永远持续下去。

    因此,出于这个原因,您不能在您的示例中在 this 或 this.props 上使用 JSON.stringify(this.props 的属性 children 是该问题的部分原因)。

    您会注意到您可以将this.state 字符串化,因为这是一个不引用任何其他 React 对象的普通对象:

    > JSON.stringify(this.state);
    "{"selected":0}"
    

    编辑:对您来说最好的方法是只使用console.log 而不使用JSON.stringify:

    console.log("this.props.children[this.state.selected]---->", this.props.children[this.state.selected]);
    

    您可以向console.log 添加多个参数并用逗号分隔它们,然后浏览器控制台本身应该以可查看的格式打印它。

    【讨论】:

    • 但是如何打印这个值并查看 JSON.stringify(this.props)
    • @texirv - 如果您只是打印出来亲自查看,则不需要JSON.stringify 它。只需将其添加到您的console.log,浏览器控制台就会使其可见。请参阅我编辑的答案。
    • 你能帮我解决这个问题吗stackoverflow.com/questions/40498339/…
    • 这是一个不同的问题,我来看看。如果我已正确回答此问题,请将其标记为您接受的答案。
    • 感谢您的帮助...我尝试调试其他问题...但无法解决。
    猜你喜欢
    • 2013-06-27
    • 2012-05-17
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 2019-01-31
    • 2021-07-23
    相关资源
    最近更新 更多