简体   繁体   English

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

[英]Using setTimeout function not working in React

am trying to use the setTimeout function if the user clicks on the button, I want it to display successfully for just 3sec, it displaying but it's not executing the 3sec time given.如果用户单击按钮,我正在尝试使用 setTimeout 函数,我希望它成功显示 3 秒,它显示但它没有执行给定的 3 秒时间。 what am I doing wrong?我究竟做错了什么?

Here's my code这是我的代码

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

you need to use a anonymous function because right now you're calling the function when using setTimeout您需要使用匿名函数,因为现在您在使用 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) executes func after n milliseconds. setTimeout(func,n)n毫秒执行func

If you want the message to be displayed during 3s,如果您希望消息3 秒内显示,

  1. Set the message immediately立即设置消息
  2. Clear the message after 3s. 3秒清除消息。

Inside your then callback,在您的then回调中,

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

However due the asynchronous nature of state updates, the setTimeout may be "set" before the success message, resulting in the message for being shown for, example 2.993 seconds.然而,由于状态更新的异步特性,setTimeout 可能会在成功消息之前“设置”,从而导致消息显示时间为 2.993 秒。

A more precise solution would be:更精确的解决方案是:

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);
         }); 
    })
    // ...
} 

Here the 2nd callback argument of setState is run, after message is set.在设置消息之后,这里运行setState的第二个回调参数。

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

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