React挂钩-清除超时和间隔的正确方法
我不明白为什么当我使用setTimeout
函数时,我的react组件开始进入无限console.log。一切正常,但PC开始陷入困境。有人说超时中的功能会更改我的状态,并会重新渲染组件,设置新的计时器等。现在,我需要了解如何清除它是正确的。
export default function Loading() { // if data fetching is slow, after 1 sec i will show some loading animation
const [showLoading, setShowLoading] = useState(true)
let timer1 = setTimeout(() => setShowLoading(true), 1000)
console.log('this message will render every second')
return 1
}
清除不同版本的代码无法帮助:
const [showLoading, setShowLoading] = useState(true) let timer1 = setTimeout(() => setShowLoading(true), 1000)
useEffect(
() => {
return () => {
clearTimeout(timer1)
}
},
[showLoading]
)
回答:
__useEffect
每次运行时useEffect
都会在运行中 返回
函数(首次运行在组件安装上除外)。考虑一下它,因为每次useEffect
执行新的执行时,旧的执行都会被删除。
这是使用和清除超时或间隔的一种有效方法:
export default function Loading() { const [showLoading, setShowLoading] = useState(false)
useEffect(
() => {
let timer1 = setTimeout(() => setShowLoading(true), 1000)
// this will clear Timeout when component unmount like in willComponentUnmount
return () => {
clearTimeout(timer1)
}
},
[] //useEffect will run only one time
//if you pass a value to array, like this [data] than clearTimeout will run every time this value changes (useEffect re-run)
)
return showLoading && <div>I will be visible after ~1000ms</div>
}
如果您需要清除超时或间隔时间不在某个地方:
export default function Loading() { const [showLoading, setShowLoading] = useState(false)
const timerToClearSomewhere = useRef(false) //now you can pass timer to another component
useEffect(
() => {
timerToClearSomewhere.current = setInterval(() => setShowLoading(true), 50000)
return () => {
clearInterval(timerToClearSomewhere.current)
}
},
[]
)
//here we can imitate clear from somewhere else place
useEffect(() => {
setTimeout(() => clearInterval(timerToClearSomewhere.current), 1000)
}, [])
return showLoading ? <div>I will never be visible because interval was cleared</div> : <div>showLoading is false</div>
}
以上是 React挂钩-清除超时和间隔的正确方法 的全部内容, 来源链接: utcz.com/qa/425649.html