简体   繁体   中英

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.

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

On in onClickSave the first console.log prints this: (I removed the error, required in an unimportet step)

{
    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() {
        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. If you put any json in it, the function changes it's key and values to string format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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