ReactJS:表单向数据库发送错误的日期值
我正在尝试使用Reactstrap表单将数据发送到数据库,所有数据都被正确发送,除了日期值。我输入的日期在MongoDB上保存为ReactJS:表单向数据库发送错误的日期值,reactjs,mongodb,forms,reactstrap,Reactjs,Mongodb,Forms,Reactstrap,我正在尝试使用Reactstrap表单将数据发送到数据库,所有数据都被正确发送,除了日期值。我输入的日期在MongoDB上保存为1970-01-01T00:00:00.000+00:00,我不知道为什么 当我通过邮递员发送所有内容时,它会保存正确的值,但我想从表单中提交它 表单日期字段: <Form onSubmit={this.onSubmit}> <FormGroup> <Label className="lead">
1970-01-01T00:00:00.000+00:00
,我不知道为什么
当我通过邮递员发送所有内容时,它会保存正确的值,但我想从表单中提交它
表单日期字段:
<Form onSubmit={this.onSubmit}>
<FormGroup>
<Label className="lead">Horário local da leitura</Label>
<Input type="text" name="hora_leitura" required />
onChange函数
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
输入后API代码:
router.post("/", (req, res) => {
const {
hora_leitura, pressao_atm, temp_ar, temp_min, temp_max, umid_rel,
umid_min, rad_solar, chuva_ac_dia, inten_vento, direc_vento,
} = req.body;
Entry.findOne({ hora_leitura }).then((isMatch) => {
if (isMatch)
return res
.status(400)
.json({ msg: "Uma entrada com essa data já existe" });
else {
const newEntry = new Entry({
hora_leitura, pressao_atm, temp_ar, temp_min, temp_max, umid_rel,
umid_min,rad_solar, chuva_ac_dia, inten_vento, direc_vento,
});
newEntry.save().then((entry) => res.json(entry));
}
});
});
不知道为什么它没有发送正确的日期。如果你能帮我解释一下你的答案,那就太好了
编辑:
在我的EntryModal
类状态中,我有
state = {
modal: false,
added: false,
hora_leitura: new Date(),
pressao_atm: 0,
temp_ar: 0,
temp_min: 0,
temp_max: 0,
umid_rel: 0,
umid_min: 0,
rad_solar: 0,
chuva_ac_dia: 0,
inten_vento: 0,
direc_vento: "",
msg: null,
};
我在
onSubmit()
上调用addEntry
的上方放了一个console.log
,它显示了hora_leitura
作为表单发送的确切日期,而不是我插入的日期。我不知道我的代码是否在onChange
上读取了正确的日期值经过一些测试后,我注意到,要更改我在state上设置的值,我必须在元素上调用onChange
,就像我在表单上的每个输入上一样,但在
上,所以我在这个输入中输入的任何值都无关紧要
我刚刚将输入更改为:
<Input
type="text"
name="hora_leitura"
placeholder="2020-06-12T09:00:00.000"
onChange={this.onChange} // this is what was missing
required
/>
它工作得很好。如何在该州保存日期,或者如何选择更准确的日期?@Slavian首先我在该州设置了日期:0,然后它应该通过
this.setState({[e.target.name]:e.target.value})更新为新值与表单位于同一类中的onChange方法上的code>。
<Input
type="text"
name="hora_leitura"
placeholder="2020-06-12T09:00:00.000"
onChange={this.onChange} // this is what was missing
required
/>