为什么在这个反应示例中使用 useRef ?只是为了概念演示? [英] Why using useRef in this react example? just for concept demostration?

查看:60
本文介绍了为什么在这个反应示例中使用 useRef ?只是为了概念演示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道 useRef 在示例中的作用是什么:https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables:

Just wonder what purpose the useRef serve here in example: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables:

function Timer() {
  const intervalRef = useRef();

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

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

我尝试过并且可以在没有 useRef 的情况下实现相同的效果,如下所示:

I tried and can achieve the same without useRef as below:

function Timer() {
  const interval = null;

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

  // ...
  function handleCancelClick() {
    clearInterval(interval);
  }
  // ...
}

所以说但如果我们想从事件处理程序中清除间隔是有用的"来自反应文档和这个答案:是否必须使用 useRef Hook 在 React 中设置和清除间隔?,几乎没有任何意义.

So the saying "but it’s useful if we want to clear the interval from an event handler" from the react doc and this answer: Is useRef Hook a must to set and clear intervals in React?, just mean almost nothing at all.

推荐答案

仅当您不想在 handleCancelClick 中停止计时器并将所有逻辑保留在单个 useEffect 中时才可以>(这种情况非常罕见).

It's fine only if you don't want stopping timer in handleCancelClick and keep all logic inside single useEffect(which would be really rare case).

看,如果您在运行计时器和 handleCancelClick 之间获得任何重新渲染(由于任何 useState 条目更改或道具更改),您将获得该变量 const interval = null; 并且点击时什么都不会发生(clearTimeout(null); 什么都不做).

See, if you get any re-render(because of any useState entry changed or props changed) between running timer and handleCancelClick you will get that variable const interval = null; and nothing will happen on click(clearTimeout(null); does nothing).

不知道如何在不保留渲染之间的数据的情况下处理这种情况.

Don't see how that can be handled without preserving data between renders.

这篇关于为什么在这个反应示例中使用 useRef ?只是为了概念演示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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