Date变量即使在提交表单之后也保持不变



当点击onSubmit时尝试设置日期,但即使在setDate之后它仍然保持相同的状态

const onSubmit = e => {
e.preventDefault();
setDate(moment(Date.now()).format(format1));

axios
.post('http://localhost:4000/questions', {
ques: ques,
quesBrief: quesBrief,
hashes: hashes,
author: author,
date: date,
})
.then(res => {
console.log(res.data);
history.push('/');
})
.catch(err => {
console.log(err);
});
};
return (
<div className='mt-4 w-1/2'>
<button className=' w-40 text-md px-4 ml-2 mt py-3 rounded bg-orange-500 text-white font-bold 
hover:bg-gray-1100 hover:text-orange-500  lg:mt-0 transition ease-out duration-500'
onClick={onSubmit}
>
Post Question
</button>
)

点击onSubmit后,我有了这个对象

{ques: 'fjfds', quesBrief: 'sdagd', hashes: '#dsa', author: 'Me2', date: '', …}
author: "Me2"
date: ""
hashes: "#dsa"
id: "Vv7I1c9"
ques: "fjfds"
quesBrief: "sdagd"

日期保持空白。但是,如果我提交第二次,日期设置成功。有人能解释一下这种行为吗?

在React中设置状态是异步的。查看新状态值的唯一方法是在呈现之后。如果您想立即使用该值,请使用变量。

const onSubmit = e => {
e.preventDefault();
let newDate = moment(Date.now()).format(format1);
setDate(newDate);

axios
.post('http://localhost:4000/questions', {
ques: ques,
quesBrief: quesBrief,
hashes: hashes,
author: author,
date: newDate,
})
.then(res => {
console.log(res.data);
history.push('/');
})
.catch(err => {
console.log(err);
});
};

相关内容

最新更新