![](/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.