开发者问题收集

react useRef:当前值未定义

2020-12-24
3166

我正在按照 useState useRef 钩子的初学者教程,尝试在 React 中实现一个简单的计时器。

我正在使用 interval 变量来存储 setInterval() 的值

单击开始按钮时,我能够正确地将间隔值记录到控制台。 但是,单击停止按钮时, interval.current 在控制台中记录为 undefined 。因此, stopTimer() 无法按预期运行。

为什么 interval.current 会在 startTimer 中明确设置(并记录在那里)时打印 undefined?我这里遗漏了什么?

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

const pad = (time) => {
  return time.toString().padStart(2, "0");
};


function App() {
  const [title, setTitle] = useState("Pomodoro!");
  const [timeLeft, setTimeLeft] = useState(5);
  const interval = useRef(null);

  const startTimer = () => {
    interval.current = setInterval(() => {
      setTimeLeft((timeLeft) => {
        if (timeLeft >= 1) {
          return timeLeft - 1;
        }
        return 0;
      });
    }, 1000);
    console.log(interval.current, " :in start");
  }

  const stopTimer = (interval) => {
    console.log("in stop: ", interval.current);
    clearInterval(interval.current);
  }

  const resetTimer = () => { }

  const minutes = pad(Math.floor(timeLeft / 60));
  const seconds = pad((timeLeft - minutes * 60));


  return (

    <div>
      <div>{title}</div>
      <div>
        <span>{minutes}</span>
        <span>:</span>
        <span>{seconds}</span>
      </div>
      <div>
        <button onClick={startTimer}>Start</button>
        <button onClick={stopTimer}>Stop</button>
        <button onClick={resetTimer}>Reset</button>
      </div>
    </div>
  );
}

export default App;

控制台中的输出

6 " :in start" in stop: undefined

谢谢

2个回答

我相信这是因为您将一个名为 interval 的较低范围变量传递给 stopTimer ,但是当您调用 stopTimer 时您没有传递参数,因此在访问它时它是未定义的。

您可能指的是您已定义为 refinterval ,因此您只需访问它而不将 interval 传递给 stopTimer ,请尝试以下操作:

  const stopTimer = () => {
    console.log("in stop: ", interval.current);
    clearInterval(interval.current);
  }
SomoKRoceS
2020-12-25

考虑到您的代码的作用,我认为 interval 应该是状态变量,而不是引用。也就是说,您应该使用

const [interval, setInterval] = useState(null);

而不是 const interval = useRef(null);

引用用于链接到 DOM 元素(例如,您希望在单击按钮时引用的表单元素)。只有当引用变量正确引用 DOM 元素时,才会定义其 current 属性。

alexis_thual
2020-12-25