在 React 中设置和清除间隔必须使用 useRef Hook 吗? [英] Is useRef Hook a must to set and clear intervals in React?

查看:30
本文介绍了在 React 中设置和清除间隔必须使用 useRef Hook 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在了解 useRef 钩子及其用法.访问 DOM 是我理解的一个非常直接的用例.第二个用例是 ref 的行为类似于类组件中的实例字段.而 react 文档 提供了一个从单击处理程序设置和清除时间间隔的示例.我想知道,如果不需要从点击处理程序中取消时间间隔,我们是否可以像下面这样使用在 useEffect 中声明的局部变量来设置和清除间隔?还是使用文档中提到的 ref 总是要采用的方法?

useEffect(() => {const id = setInterval(() => {//...});返回 () =>{clearInterval(id);};})

解决方案

As 在您共享的文档中说明;

<块引用>

如果我们只是想设置一个间隔,我们就不需要 ref(id 可以是效果的局部).

 useEffect(() => {const id = setInterval(() => {setCounter(prev => prev + 1);}, 1000);返回 () =>{clearInterval(id);};});

<块引用>

但如果我们想从事件处理程序中清除间隔,这很有用:

//...函数 handleCancelClick() {clearInterval(intervalRef.current);}//...

I'm currently understanding the useRef hook and its usage. Accessing the DOM is a pretty straight forward use case which I understood. The second use case is that a ref behaves like an instance field in class components. And the react docs provide an example of setting and clearing a time interval from a click handler. I want to know, if cancelling the time interval from a click handler is not required, can we set and clear intervals with local variables declared within useEffect like below? Or is using a ref as mentioned in the docs always the approach to be taken?

useEffect(() => {
 const id = setInterval(() => {
  // ...
  });
  return () => {
    clearInterval(id);
  };
})

解决方案

As stated at the docs you shared;

If we just wanted to set an interval, we wouldn’t need the ref (id could be local to the effect).

  useEffect(() => {
    const id = setInterval(() => {
      setCounter(prev => prev + 1);
    }, 1000);
    return () => {
      clearInterval(id);
    };
  });

but it’s useful if we want to clear the interval from an event handler:

// ...
function handleCancelClick() {
  clearInterval(intervalRef.current);
}
  // ...

这篇关于在 React 中设置和清除间隔必须使用 useRef Hook 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆