为什么 clearTimeout 不清除此react组件中的超时?

IT技术 javascript reactjs settimeout cleartimeout
2021-04-30 11:11:51

我试图在启动新的超时之前清除以前的超时,因为我希望消息显示 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);
  }

...但显然违背了目的,因为它会立即消除超时。在实践中,我应该能够每两秒触发一次 initMessage()并且永远不会看到“擦除消息”记录到控制台。

3个回答

问题是在每次渲染时, 的值t都会重置为 null。一旦您调用updateMessage,它将触发重新渲染并失去它的value。功能性react组件内的任何变量在每次渲染时都会重置(就像在render基于类的组件功能内一样)。如果要保留引用,则需要保存tusing的值,setState以便可以调用clearInterval.

但是,另一种解决方法是PromisesetTimeout通过使其成为Promise,您可以消除需求,t因为它在setTimeout完成之前不会解决完成后,您可以updateMessage('')重置message. 这可以避免您在引用t.

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

const initMessage = async (msg) => {
  updateMessage(msg);
  await clearLogger();
}

我用 useEffect 解决了这个问题。您想清除返回函数中的超时

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

useEffect(() => {
  const t = setTimeout(() => {
    console.log('wiping message');
    updateMessage('');
  }, 4000);

  return () => {
    clearTimeout(t)
  }
}, [message])



function initMessage(msg) {
  updateMessage(msg);
}

在 clearTimeout() 完成后尝试执行 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);
});