[英]My json object formed through a form is blank
I'm filling out a form, until then, okay, the problem is when I press the input to send and form a json object with the states that I set up in my constructor, the json object that appears in my console.log is empty, then , by pressing the input with the same values again on the form, the json object this time appears with duplicate values. 我正在填写一个表单,直到那时,好吧,问题是当我按下输入发送并形成一个json对象,其中包含我在构造函数中设置的状态时,我的console.log中出现的json对象是为空,然后,通过在窗体上再次按下具有相同值的输入,此时json对象显示重复值。
return after an input
.
{
"string":"",
"uint":""
}
return after two inputs. (duplicate values)
{
"string":[
"sensor1",
"sensor1"
],
"uint":[
"1",
"1"
]
}
import React, { Component } from 'react';
export default class DHT11 extends Component {
constructor(props) {
super(props);
this.arrayStr = [];
this.arrayUint = [];
this.auxUint = '';
this.auxStr = '';
this.state = {
string: '',
uint: '',
greatness: ''
}
}
handleSubmit = e => {
e.preventDefault();
this.arrayStr.push(this.auxStr);
this.arrayUint.push(this.auxUint);
this.setState({ string: this.arrayStr });
this.setState({ uint: this.arrayUint });
var json = JSON.stringify(this.state);
console.log(json);
}
handleChange = e => {
const { name, value } = e.target;
// console.log(name, value);
switch (name) {
case 'str':
this.auxStr = (value);
break;
case 'uint':
this.auxUint = (value);
break;
}
}
render() {
return (
<form onSubmit={this.handleSubmit} noValidate>
<div className='id_sensor'>
<label htmlFor="ID"> ID Sensor </label>
<input
placeholder=""
type="text"
name="uint"
noValidate
onChange={this.handleChange}
/>
</div>
<div className='id_sensor'>
<label htmlFor="Name"> Name </label>
<input
placeholder=""
type="text"
name="str"
noValidate
onChange={this.handleChange}
/>
</div>
<div className="createAccount">
<button type="submit">Send Values</button>
</div>
</form>
)
}
}
It might be that setState is not guaranteed to be synchronous and has not finished when you call console.log. 可能是setState不能保证同步,并且在调用console.log时尚未完成。 However, you can add a callback which gets called when setState has finished: 但是,您可以添加一个在setState完成时调用的回调:
this.setState({ string: this.arrayStr, uint: this.arrayUint }, () => {
var json = JSON.stringify(this.state);
console.log(json);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.