![](/img/trans.png)
[英]Using setTimeout and accessing state is not working in React Native
[英]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 秒内显示,
在您的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.