这是一个很常见的问题。
Converting circular structure toJSON(...)之所以抛出该异常,是因为您试图打印出一个最终通过其属性之一引用自身的对象。
这是解决此问题的最简单方法之一的JSFiddle:
var a = { b: null};// Prints fineconsole.log(JSON.stringify(a, null, 3));a.b = a;// Throws an error, as a.b *is* aconsole.log(JSON.stringify(a, null, 3));当您调用时
JSON.stringify,浏览器将像一棵大树一样遍历您的对象,像分支一样遍历每个属性并将其能转换为字符串。在上面的示例中,
b最初的属性为null,这将导致成功的“字符串化”。当设置
a.b为
a自身时,我们现在得到了这种树:
a|-b: a |-b: a |-b: a ...
这种结构是 圆形的 ,因为对象引用了自身。无法将其编写为JSON,因为它将永远存在,因此会引发错误。
对于您的特定问题,这是在React中发生的,因为React对象引用了他们的父母,后者引用了他们的孩子,后者引用了他们的父母,又引用了他们的孩子…它永远存在。
所以你不能使用
JSON.stringify上
this或者
this.props在您的示例因为这个原因(
this.props有产权
children是对这一问题的部分原因)。
您会注意到,您 可以将 stringize
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并用逗号分隔,然后浏览器控制台本身应以可见格式打印它。



