我是 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 对象引用它们的父对象,引用它们的子对象,引用它们的父对象,引用它们的子对象......它会一直持续下去。
因此,出于这个原因,您不能在示例中的 this
或 this.props
上使用 JSON.stringify
(this .props
的属性 children
对这个问题负有部分责任)。
您会注意到您可以将 this.state
字符串化,因为这是一个不引用任何其他 React 对象的普通对象:
> JSON.stringify(this.state);
"{"selected":0}"
编辑:对你来说最好的可能是没有 JSON.stringify
的 console.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/