【问题标题】:react useRef : current value is undefined反应 useRef :当前值未定义
【发布时间】:2021-04-03 06:02:26
【问题描述】:

我正在关注 useStateuseRef 钩子的初学者教程,尝试在 react 中实现一个简单的计时器。

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

点击开始按钮后,我可以正确地控制台记录时间间隔的值。 然而,在单击停止按钮时,interval.current 被控制台记录为undefinedstopTimer() 因此无法按预期运行。

为什么在 startTimer 中明确设置(并记录在那里)时,interval.current 打印未定义?我在这里错过了什么?

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“:在开始” 停止:未定义

谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

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

    您可能指的是interval,您已定义为ref,因此您只需访问它而不将interval 传递给stopTimer,试试这个:

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

    【讨论】:

      【解决方案2】:

      考虑到你的代码在做什么,我相信interval 应该是一个状态变量而不是一个引用。也就是说,你应该使用

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

      而不是const interval = useRef(null);

      Refs 用于链接到 DOM 元素(例如,您希望在单击按钮时引用的表单元素)。只有当一个 ref 变量正确引用了一个 DOM 元素时,它们的 current 属性才被定义。

      【讨论】:

      • 虽然 ref 常用于锚定 DOM 元素,但并不局限于此。
      猜你喜欢
      • 1970-01-01
      • 2021-05-02
      • 2021-10-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2021-04-01
      • 1970-01-01
      相关资源
      最近更新 更多