繁体   English   中英

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

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

我做了什么:

我在 React 中创建了一个类来处理 React HTML Form 的表单控件。

创建一个对象,如:


  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);
   }
 }

因此,如果我将名称字段从“aaa”更改为“aab”,则会出现以下问题

onClickSave ,第一个console.log打印:(我删除了错误,在onClickSave步骤中需要)

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

第二个这样:

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

有人能告诉我为什么值不同吗?


编辑:

好的,我想我知道错误在哪里:

在 onClickSave() 函数中,我回调到另一个函数,例如:

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

没有回调,值相同,有回调,值不同

这是 JSON.stringify(obj) 函数的正常行为。 如果您在其中放入任何 json,该函数会将其键和值更改为字符串格式。

暂无
暂无

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

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