繁体   English   中英

为什么当我调用函数“StopTimer”函数时我的变量“intervalId”没有更新值?

[英]Why my variable "intervalId" is not getting the value updated when I call the function "StopTimer" function?

这是我的简单代码:

import React, { useState } from "react";
import "./App.css";

function App() {
  const [time, setTime] = useState(0);
  var intervalId;

  function startTimer() {
    intervalId = setInterval(() => {
      setTime(time => time + 1);
    }, 1000);
    console.log("My interval id is: ", intervalId);
  }

  function stopTimer() {
    console.log("Clearing intervalId", intervalId);
    clearInterval(intervalId);
  }

  return (
    <div className="App">
      <div>{time}</div>
      <div>
        <button onClick={startTimer}>Start time</button>
        <button onClick={stopTimer}>Stop time</button>
      </div>
    </div>
  );
}

这是错误的表示

我按下Start Time 按钮,然后按下Stop Time Button ,但是我在 stopTimer 函数中的变量 intervalId 没有从 setInterval 函数中获取更新的值。 为什么?。

因为intervalId与调用startTimer时作用域内的变量不同。 它将在所有后续渲染中undefined (当time改变状态时引起)

在 React 中,如果你想在组件的整个生命周期中“保持一个值”,你可以为它使用ref

  // ....
  var intervalId = React.useRef();
  // ....
  intervalId.current = setInterval(() => {
  // ...
  clearInterval(intervalId.current);

由于每次更改状态 ( setTime ) 时都会调用App ,因此您将获得局部变量的新值。

一种选择是在您的状态中包含变量。

function App() {
  var [time, setTime] = useState(0);
  var [intervalId, setIntervalId] = useState(0);

  function startTimer() {
    setIntervalId(intervalId => setInterval(() => {
      setTime(time => time + 1);
    }, 1000));
  }

  function stopTimer() {
    clearInterval(intervalId);
  }

  return (
    <div className="App">
      <div>{time}</div>
      <div>
        <button onClick={startTimer}>Start time</button>
        <button onClick={stopTimer}>Stop time</button>
      </div>
    </div>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM