简体   繁体   English

在 JSON.stringify(obj) 之后反应 js 不同的值

[英]React js different values after JSON.stringify(obj)

What I did:我做了什么:

I created a class in React to handle the form control of a react HTML Form.我在 React 中创建了一个类来处理 React HTML Form 的表单控件。

Create an object like:创建一个对象,如:


  class FormController extends Component {
   
    constructor(props) {
       super(props);
       this.onClickSave = this.onClickSave.bind(this);

       var tempFormInputs = {};

       //read all (html)input names and values from children and create an 
       // object for each pair into the tempform

       var currentElement;
       for (var x = 0; x < this.props.children.props.children.length; x++) 
       {
            currentElement= this.props.children.props.children[x]
            tempFormInputs[currentElement.props.name] = { 
                  value: '',
                  error: false,
                  required: currentElement.props.required
            }
       }
    
       this.state = {
            formularData: tempFormInputs,
       }
    }
       //function called from child on change
       onComponentChange(value, Evname) {
        this.state.formularData[Evname].value = value;
       }
   
   //function connected to a Button
   //triggered on click

   onClickSave() {
       console.log(this.state.formularData);
       console.log(JSON.stringify(this.state.formularData));
       this.props.submitCallback(this.formularData);
   }
 }

So if I change the name field from 'aaa' to 'aab', the following problem occurred因此,如果我将名称字段从“aaa”更改为“aab”,则会出现以下问题

On in onClickSave the first console.log prints this: (I removed the error, required in an unimportet step)onClickSave ,第一个console.log打印:(我删除了错误,在onClickSave步骤中需要)

{
    name: {value: "aaa"}
    serviceID: {value: "1"}
    ...
}

The second one this:第二个这样:

{"name":{"value":"aab"},"serviceID":{"value":"1"}}

Can someone tell me why the values are different?有人能告诉我为什么值不同吗?


EDIT:编辑:

okay i think i figured out where the error is:好的,我想我知道错误在哪里:

in the onClickSave() function i callback to another function, like:在 onClickSave() 函数中,我回调到另一个函数,例如:

 onClickSave() {
        console.log(this.state.formularData);
        console.log(JSON.stringify(this.state.formularData));
        this.props.submitCallback(this.formularData);
}

without the callback the values are the same, with the callback the values differ没有回调,值相同,有回调,值不同

This the normal behavior of JSON.stringify(obj) function.这是 JSON.stringify(obj) 函数的正常行为。 If you put any json in it, the function changes it's key and values to string format.如果您在其中放入任何 json,该函数会将其键和值更改为字符串格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM