简体   繁体   English

clearinterval 在反应钩子中不起作用

[英]clearinterval is not working in react hooks

I am creating a simple timer, when the user clicks on start timer, the timer start's and when the user clicks on stop timer the timer stops.我正在创建一个简单的计时器,当用户单击开始计时器时,计时器开始,当用户单击停止计时器时,计时器停止。 But clearinterval is not working, i even tried但是 clearinterval 不起作用,我什至尝试过

import React, { useEffect, useState } from "react";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";

const App = () => {
  const [seconds, setSeconds] = useState(0);
  const [minutes, setminutes] = useState(0);
  const [hour, sethour] = useState(0);
  const [start, setStart] = useState(false);

  const handleStartBtn = () => {
    setStart(!start);
    let id;
    if (!start) {
      id = setInterval(() => setSeconds(sec => sec + 1), 1000);
    } else {
      clearInterval(id);
    }
  };

  return (
    <div className="timer">
      <Container>
        <Row>
          <Col>
            <span className="mr-3">hour:-{hour}</span>
            <span className="mr-3">minutes:-{minutes}</span>
            <span className="mr-3">seconds:-{seconds}</span>
          </Col>
        </Row>
        <Row>
          <Button onClick={handleStartBtn}>{!start ? "start" : "stop"}</Button>
        </Row>
      </Container>
    </div>
  );
};

export default App;

The only time clearInterval is ever called, id is undefined.唯一一次调用clearInterval时, id是未定义的。 (That is, it's declared as a variable within that function's scope but has no value set to it.) You need to store the value of that id so you can access it later. (也就是说,它在该函数的 scope 中声明为变量,但没有设置任何值。)您需要存储该id的值,以便以后访问它。 Since this is a React component, state is a reasonable place to store it.由于这是一个 React 组件,因此 state 是存储它的合理位置。 For example:例如:

const [intervalId, setIntervalId] = useState(0);

Then set that state when setting the interval:然后在设置间隔时设置state:

setIntervalId(setInterval(() => setSeconds(sec => sec + 1), 1000));

And then when you clear the interval you can use the ID value from state:然后,当您清除间隔时,您可以使用 state 中的 ID 值:

clearInterval(intervalId);

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

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