Javascript 在 React 中将组件状态转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47888994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:58:29  来源:igfitidea点击:

Converting component state to JSON in React

javascriptjsonreactjsobject

提问by Spectrum

I am new to React JS. I wanted to convert the component state data into a JSON object. Is it possible? If so, how?

我是 React JS 的新手。我想将组件状态数据转换为 JSON 对象。是否可以?如果是这样,如何?

Sample state :

样品状态:

this.state = {
    name : "Example",
    age : "21",
    description : "Some text here."
}

That's the whole question. I would appreciate it if you could tell me where I can find simple tutorials to do more advanced things in React (like sending/receiving JSON to/from a server, doing redirects, creating menus, etc). I know I sound vague, and I don't expect very specific answers(if any) to this.

这就是整个问题。如果您能告诉我在哪里可以找到简单的教程来在 React 中做更高级的事情(例如向/从服务器发送/接收 JSON、进行重定向、创建菜单等),我将不胜感激。我知道我听起来很含糊,我不希望对此有非常具体的答案(如果有的话)。

回答by Mihai Alexandru-Ionut

Just use JSON.stringifymethod in order to turn an javascriptobject into JSONtextand store that JSONtext in a string.

只需使用JSON.stringifymethod 即可将javascript对象转换为JSON文本并将该JSON文本存储在字符串中

Also, you can use JSON.parsewhich turns a string of JSONtext into a Javascriptobject.

此外,您可以使用JSON.parsewhich 将一串JSON文本转换为一个Javascript对象。

let state = {
    name : "Example",
    age : "21",
    description : "Some text here."
}
console.log(state);
console.log(JSON.stringify(state));