我怎样才能清理像这样的函数setTimeout
or setInterval
在 React 的事件处理程序中?还是说没有必要这样做?
import React from 'react'
function App(){
return (
<button onClick={() => {
setTimeout(() => {
console.log('you have clicked me')
//How to clean this up?
}, 500)
}}>Click me</button>
)
}
export default App
是否有必要取决于回调的作用,但当然,如果组件被卸载,它的作用几乎无关紧要,您确实需要取消计时器/清除间隔。
要在像您这样的函数组件中执行此操作,您可以使用useEffect
具有空依赖项数组的清理函数。您可能想将计时器句柄存储在ref
.
(FWIW,我还将函数定义在onClick
属性,只是为了清楚起见。)
import React, {useEffect, useRef} from 'react';
function App() {
const instance = useRef({timer: 0});
useEffect(() => {
// What you return is the cleanup function
return () => {
clearTimeout(instance.current.timer);
};
}, []);
const onClick = () => {
// Clear any previous one (it's fine if it's `0`,
// `clearTimeout` won't do anything)
clearTimeout(instance.current.timer);
// Set the timeout and remember the value on the object
instance.current.timer = setTimeout(() => {
console.log('you have clicked me')
//How to clean this up?
}, 500);
};
return (
<button onClick={onClick}>Click me</button>
)
}
export default App;
您存储为参考的对象通常是放置本来要穿上的东西的有用地方this
在类组件中。
(如果你想避免重新渲染button
当组件中的其他状态发生变化时(现在没有其他状态,所以不需要),您可以使用useCallback
for onClick
so button
总是看到相同的功能。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)