[英]Does clearing timeout/interval have to be inside `useEffect` react hook?
I'm wondering what is the correct way and best practice to clear timeouts/intervals when using React hooks.我想知道在使用 React 钩子时清除超时/间隔的正确方法和最佳实践是什么。 For example I have the following code:
例如我有以下代码:
import React, { useState, useEffect, useRef } from 'react';
const Test = () => {
const id = useRef(null)
const [count, setCount] = useState(5)
const [timesClicked, setTimesClicked] = useState(0)
if (!count) {
clearInterval(id.current)
}
useEffect(() => {
id.current = setInterval(() => {
setCount(count => count -1)
}, 1000)
return () => {
clearInterval(id.current)
}
}, [])
const onClick = () => setTimesClicked(timesClicked => timesClicked + 1)
return (
<div>countdown: {count >= 0 ? count : 0}
<hr />
Clicked so far: {timesClicked}
{count >= 0 && <button onClick={onClick}>Click</button>}
</div>
)
}
When count
equals 0 the interval is cleared in the body of the Test
function.当
count
等于 0 时,间隔在Test
function 的主体中被清除。 In most of the examples I've seen on the Internet interval is cleared inside useEffect
, is this mandatory?在我在 Internet 上看到的大多数示例中,间隔在
useEffect
中被清除,这是强制性的吗?
You must be sure to clear all intervals before your component gets unmounted.您必须确保在卸载组件之前清除所有间隔。 Intervals never disappear automatically when components get unmounted and to clear them,
clearInterval
is often called inside useEffect(() => {}, []).当组件被卸载并清除它们时,间隔永远不会自动消失,
clearInterval
通常在 useEffect(() => {}, []) 中调用。
The function retured in useEffect(() => {}, []) gets called when the compoment is unmounted.在卸载组件时调用 useEffect(() => {}, []) 中返回的 function。
return () => {
clearInterval(id.current)
}
You can see that intervals set inside a component never disappears automatically by checking this sandbox link.通过检查此沙箱链接,您可以看到组件内设置的间隔永远不会自动消失。 https://codesandbox.io/s/cool-water-oij8s
https://codesandbox.io/s/cool-water-oij8s
Intervals remain forever unless clearInterval
is called.除非调用
clearInterval
,否则间隔将永远保留。
setInterval
is a function
which is executed repeatedly and it returns an id
of the interval. setInterval
是一个重复执行的function
并返回间隔的id
。 When you call clearInterval
with this id, you stop that function
from repeating.当您使用此 ID 调用
clearInterval
时,您会阻止function
重复。 It's not mandatory to do it inside a certain function
, you need to clear it when you no longer want that function
to be called subsequently.在某个
function
内执行它不是强制性的,当您不再希望随后调用function
时,您需要清除它。 You can call it in the function
you return as a result of useEffect
, if that's what you need.如果您需要的话,您可以在由于
function
返回的useEffect
中调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.