小编典典

VM1374:32未捕获的TypeError:将圆形结构转换为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]));

阅读 257

收藏
2020-07-22

共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最初的属性为null,这将导致成功的“字符串化”。当设置a.ba自身时,我们现在得到了这种树:

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

这种结构是 圆形的 ,因为对象引用了自身。无法将其编写为JSON,因为它将永远存在,因此会引发错误。

对于您的特定问题,这是在React中发生的,因为React对象引用了他们的父母,后者引用了他们的孩子,后者引用了他们的父母,又引用了他们的孩子…它永远存在。

所以你不能使用JSON.stringifythis或者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并用逗号分隔,然后浏览器控制台本身应以可见格式打印它。

2020-07-22