3 回答
![?](http://img1.sycdn.imooc.com/533e4c9c0001975102200220-100-100.jpg)
TA贡献1765条经验 获得超5个赞
问题是在每次渲染时, 的值t都会重置为 null。一旦您调用updateMessage,它将触发重新渲染并失去它的价值。功能性反应组件内的任何变量在每次渲染时都会重置(就像在render基于类的组件的功能内一样)。如果要保留引用,则需要保存tusing的值,setState以便可以调用clearInterval.
但是,另一种解决方法是承诺setTimeout. 通过使其成为承诺,您可以消除需求,t因为它在setTimeout完成之前不会解决。完成后,您可以updateMessage('')重置message. 这可以避免您在引用t.
clearLogger = () => {
return new Promise(resolve => setTimeout(() => updateMessage(''), resolve), 5000));
};
const initMessage = async (msg) => {
updateMessage(msg);
await clearLogger();
}
![?](http://img1.sycdn.imooc.com/54584e120001811202200220-100-100.jpg)
TA贡献1829条经验 获得超7个赞
我用 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);
}
![?](http://img1.sycdn.imooc.com/545865890001495702200220-100-100.jpg)
TA贡献2036条经验 获得超8个赞
在 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);
});
添加回答
举报