Javascript 在JSON.stringify(obj)之后反应js不同的值
我所做的: 我在React中创建了一个类来处理React HTML表单的表单控件 创建一个对象,如:Javascript 在JSON.stringify(obj)之后反应js不同的值,javascript,reactjs,Javascript,Reactjs,我所做的: 我在React中创建了一个类来处理React HTML表单的表单控件 创建一个对象,如: class FormController extends Component { constructor(props) { super(props); this.onClickSave = this.onClickSave.bind(this); var tempFormInputs = {}; //read al
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);
}
}
第二个是:
{"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,函数会将其键和值更改为字符串格式。我的问题不是字符串格式,而是值不同,我不明白为什么您要直接改变状态而不使用
setState
?控制台输出是活动的,我猜Console.log的输出是活动的(此.state.formularData)
在这两行运行后立即更改;stringify行显示日志记录时的数据,另一行显示当前内容。另外,为什么构造函数中有onComponentChange
方法?这看起来像是语法错误。@adiga我现在不想更新组件time@adigaonComponentChange方法i对不起,她现在在外面,是个打字错误
onClickSave() {
console.log(this.state.formularData);
console.log(JSON.stringify(this.state.formularData));
this.props.submitCallback(this.formularData);
}