【问题标题】:Why my variable "intervalId" is not getting the value updated when I call the function "StopTimer" function?当我调用函数“StopTimer”函数时,为什么我的变量“intervalId”没有更新值?
【发布时间】:2020-02-29 16:41:01
【问题描述】:

这是我的简单代码:

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>
  );
}

Here is the representation of the error

我按开始时间按钮,然后按停止时间按钮,但我在stopTimer 函数中的变量intervalId 没有从setInterval 函数获取更新值。为什么?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      由于每次更改状态 (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>
        );
      }
      

      【讨论】:

        猜你喜欢
        • 2023-02-10
        • 2023-02-25
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多