【问题标题】:Date variable remains same even after submitting the form即使在提交表单后,日期变量也保持不变
【发布时间】:2021-11-18 08:01:14
【问题描述】:

点击 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>
)

点击提交后,我就有了这个对象

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

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

【问题讨论】:

    标签: reactjs onclick event-listener use-state onsubmit


    【解决方案1】:

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

    【讨论】:

    • 不,不工作,仍然显示相同。而且我之前也使用过 react-time。所以它说给 react-time-ago 的日期无效。
    • 刚刚在我的代码中看到了一个错误。已经修好了。要使用的变量是newDate。请立即查看
    • 我也修好了。我使用了一个 useEffect 以便它在渲染后设置 setDate。 useEffect(() => { setDate(moment(Date.now()).format(format1)); }, []);这行得通。谢谢。
    • 是的。那也行。只有在组件挂载后才能工作。
    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2019-12-03
    • 2017-04-06
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多