繁体   English   中英

使用 setTimeout 函数在 React 中不起作用

[英]Using setTimeout function not working in React

如果用户单击按钮,我正在尝试使用 setTimeout 函数,我希望它成功显示 3 秒,它显示但它没有执行给定的 3 秒时间。 我究竟做错了什么?

这是我的代码

const [message, setMessage] = useState('')

  function handleSubmit (e) {
    e.preventDefault()

      emailjs.sendForm(process.env.SERVICE_ID,process.env.TEMPLATE_ID, form.current,process.env.PUBLIC_KEY)
    .then(function(response) {
     return setTimeout(setMessage("successFully sent"), 3000)
    }, function(err) {
      console.log('FAILED...', err);
    });
  }

您需要使用匿名函数,因为现在您在使用 setTimeout 时正在调用该函数

const [message, setMessage] = useState('')

  function handleSubmit (e) {
    e.preventDefault()

      emailjs.sendForm(process.env.SERVICE_ID,process.env.TEMPLATE_ID, form.current,process.env.PUBLIC_KEY)
    .then(function(response) {
     return setTimeout(() => setMessage("successFully sent"), 3000)
    }, function(err) {
      console.log('FAILED...', err);
    });
  }

setTimeout(func,n)n毫秒执行func

如果您希望消息3 秒内显示,

  1. 立即设置消息
  2. 3秒清除消息。

在您的then回调中,

setMessage('successfully sent'); 
setTimeout(()=>{ // may start timer before message is set.
    setMessage('')
}, 3000);

然而,由于状态更新的异步特性,setTimeout 可能会在成功消息之前“设置”,从而导致消息显示时间为 2.993 秒。

更精确的解决方案是:

handleSubmit=(evt)=> { // arrow functions preserve 'this' of component
    // ....
    .then((response)=> {
         this.setState({message: 'Successfully sent'}, ()=> {
             setTimeout(()=> { // start timer after the message is set
                 this.setState({message: ''}); 
             }, 3000);
         }); 
    })
    // ...
} 

在设置消息之后,这里运行setState的第二个回调参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM