【问题标题】:Why useRef can be used to store the setInterval reference in react but not a normal variable?为什么 useRef 可以用来在 react 中存储 setInterval 引用而不是普通变量?
【发布时间】:2021-09-22 18:56:51
【问题描述】:

我正在尝试理解 React 中的 useRef 钩子。

我在 react 中创建了一个简单的时间。代码如下。

import { useRef, useState, useEffect } from 'react';

function Parent() {
  const [count,setCount]=useState(5);
  const ref=useRef(0);
//let hold=0;
  const countdown=()=>{
      ref.current=setInterval(()=>{
        // console.log('ref.current-->',ref.current);
        setCount((c)=>c-1)
       
      },1000)
  }
  useEffect(()=>{
    if(count<1)
        clearInterval(ref.current)
  },[count])
  
  return(
      <>
      <h3>Timer : {count}</h3>
      <br/>
      <button onClick={countdown}>countdown</button>
    </>
  )
}

export default Parent;

在这里,我使用钩子创建了一个 ref,并且我正在监视计数状态。当它达到 0 时,我正在调用“clearInteval”函数来清除计时器。

这段代码运行良好。

但是当我尝试使用普通变量而不是钩子创建的变量来做同样的事情时,间隔并没有被清除。

请在下面找到相同的代码。

import { useRef, useState, useEffect } from 'react';

function Parent() {
  const [count,setCount]=useState(5);
  const ref=useRef(0);
let hold=0;
  const countdown=()=>{
    hold=setInterval(()=>{
        // console.log('ref.current-->',ref.current);
        setCount((c)=>c-1)
       
      },1000)
  }
  useEffect(()=>{
    if(count<1)
        clearInterval(hold)
  },[count])
  
  return(
      <>
      <h3>Timer : {count}</h3>
      <br/>
      <button onClick={countdown}>countdown</button>
    </>
  )
}

export default Parent;

我在这里不明白什么?

这段代码应该可以在普通的 javaScript 中运行。

【问题讨论】:

  • ref 不会在每次渲染时改变(Parent 函数的执行)。同时在每次渲染时,hold 每次都被声明并初始化为新变量。同样适用于countdown 函数。

标签: reactjs react-hooks setinterval clearinterval use-ref


【解决方案1】:

const myRef = useRef() 将提供一个 ref 对象,这样myRef.current 的值将在渲染中保持不变。当您使用let myVar = something 时,myVar 将在每次渲染时重新创建,因此您每次都会丢失并替换它的值。

您的Parent 组件会在每次您的状态更改时重新渲染,因此您可以从将您的区间参考保持为useRef 的参考中受益。

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多