首页 > 解决方案 > 在 JSON.stringify(obj) 之后反应 js 不同的值

问题描述

我做了什么:

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

创建一个对象,如:


  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打印中:(我删除了错误,在 unimportet 步骤中需要)

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

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

标签: javascriptreactjs

解决方案


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


推荐阅读