VM1374:32 Uncaught TypeError:将循环结构转换为JSON(...)

4 html javascript jquery json reactjs

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

VM1374:32 Uncaught TypeError: Converting circular structure to JSON(…)
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

console.log("this.props.children[this.state.selected]---->" + JSON.stringify(this.props.children[this.state.selected]));
Run Code Online (Sandbox Code Playgroud)

And*_*ier 10

这是一个非常常见的问题.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));
Run Code Online (Sandbox Code Playgroud)

当您调用时JSON.stringify,浏览器将像一棵大树一样遍历您的对象,像分支一样沿着每个属性向下移动并将其转换为字符串.在上面的示例中,b首先属性为null,这导致成功的"字符串化".当我们设置a.ba自己,我们现在得到这个排序树的:

a
|-b: a
     |-b: a
          |-b: a
               ...
Run Code Online (Sandbox Code Playgroud)

结构是这样的循环,因为对象引用自身.没有办法把它写成JSON因为它会永远存在,所以会抛出错误.

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

所以你不能使用JSON.stringifythis或者this.props在您的示例因为这个原因(this.props有产权children是对这一问题的部分原因).

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

> JSON.stringify(this.state);
"{"selected":0}"
Run Code Online (Sandbox Code Playgroud)

编辑:最适合你的是console.log没有JSON.stringify:

console.log("this.props.children[this.state.selected]---->", this.props.children[this.state.selected]);
Run Code Online (Sandbox Code Playgroud)

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