第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 clearTimeout 不清除此反應組件中的超時?

為什么 clearTimeout 不清除此反應組件中的超時?

白衣非少年 2021-10-21 14:45:25
我試圖在啟動新的超時之前清除以前的超時,因為我希望消息顯示 4 秒并消失,除非在 4 秒之前彈出新消息。問題:舊超時正在清除當前消息,因此 clearTimeout() 在此組件中不起作用,在這種情況下:  let t; // "t" for "timer"  const [message, updateMessage] = useState('This message is to appear for 4 seconds. Unless a new message replaces it.');  function clearLogger() {    clearTimeout(t);    t = setTimeout(() => {      console.log('wiping message');      updateMessage('');    }, 4000);  }  function initMessage(msg) {    updateMessage(msg);    clearLogger();  }有趣的是,這是有效的:  function clearLogger() {    t = setTimeout(() => {      console.log('wiping message');      updateMessage('');    }, 4000);    clearTimeout(t);  }...但顯然違背了目的,因為它會立即消除超時。在實踐中,我應該能夠每兩秒觸發(fā)一次 initMessage()并且永遠不會看到“擦除消息”記錄到控制臺。
查看完整描述

3 回答

?
POPMUISE

TA貢獻1765條經(jīng)驗 獲得超5個贊

問題是在每次渲染時, 的值t都會重置為 null。一旦您調(diào)用updateMessage,它將觸發(fā)重新渲染并失去它的價值。功能性反應組件內(nèi)的任何變量在每次渲染時都會重置(就像在render基于類的組件的功能內(nèi)一樣)。如果要保留引用,則需要保存tusing的值,setState以便可以調(diào)用clearInterval.


但是,另一種解決方法是承諾setTimeout. 通過使其成為承諾,您可以消除需求,t因為它在setTimeout完成之前不會解決。完成后,您可以updateMessage('')重置message. 這可以避免您在引用t.


clearLogger = () => {

  return new Promise(resolve => setTimeout(() => updateMessage(''), resolve), 5000));

};


const initMessage = async (msg) => {

  updateMessage(msg);

  await clearLogger();

}


查看完整回答
反對 回復 2021-10-21
?
吃雞游戲

TA貢獻1829條經(jīng)驗 獲得超7個贊

我用 useEffect 解決了這個問題。您想清除返回函數(shù)中的超時


const [message, updateMessage] = useState(msg);


useEffect(() => {

  const t = setTimeout(() => {

    console.log('wiping message');

    updateMessage('');

  }, 4000);


  return () => {

    clearTimeout(t)

  }

}, [message])




function initMessage(msg) {

  updateMessage(msg);

}


查看完整回答
反對 回復 2021-10-21
?
慕桂英3389331

TA貢獻2036條經(jīng)驗 獲得超8個贊

在 clearTimeout() 完成后嘗試執(zhí)行 set timeout


clearTimeout(someVariable, function() {    

          t = setTimeout(() => {

      console.log('wiping message');

      updateMessage('');

    }, 4000);


        });


function clearTimeout(param, callback) {

  //`enter code here`do stuff

或者你也可以使用 .then() 。


clearTimeout(param).then(function(){

     t = setTimeout(() => {

          console.log('wiping message');

          updateMessage('');

        }, 4000);

});


查看完整回答
反對 回復 2021-10-21
  • 3 回答
  • 0 關(guān)注
  • 665 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號