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

标签 javascript jquery html json reactjs

我是 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]));

最佳答案

这是一个很常见的问题。 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时,浏览器会像一棵大树一样遍历你的对象,像 Twig 一样向下遍历每个属性,并将它能转换成字符串。 在上面的示例中,属性 b 最初为 null,这导致“字符串化”成功。当我们将 a.b 设置为 a 本身时,我们现在得到这种树:

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

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

对于您的特定问题,这发生在 React 中,因为 React 对象引用它们的父对象,引用它们的子对象,引用它们的父对象,引用它们的子对象......它会一直持续下去。

因此,出于这个原因,您不能在示例中的 thisthis.props 上使用 JSON.stringify(this .props 的属性 children 对这个问题负有部分责任)。

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

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

编辑:对你来说最好的可能是没有 JSON.stringifyconsole.log:

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

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

关于javascript - VM1374 :32 Uncaught TypeError: Converting circular structure to JSON(…),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40499339/

相关文章:

javascript - GetStream.io Chat API - 停止监听 Stream 中的 channel 事件

javascript - 删除li对动态li不起作用

javascript - 如何重置使用 edit-json-file 编辑的文件

jquery - 如何将几个元素居中并将其余元素附加到右侧?

javascript - 取消选中特定行中的复选框的语法是什么?

javascript - 如何将javascript动态添加到HTML并正确加载?

javascript - 无法点击下拉子菜单链接

javascript - jQuery 以通用方式隐藏除第一个图像之外的所有图像

javascript - 在 InnerHTML 之后保留 CSS

css - <th> 文本对齐兼容性