我正在尝试使用React实现一个计数器,但似乎无法正确清除间隔。

huangapple go评论65阅读模式
英文:

I am trying to implement a counter using react but cant seem to be able to clear the intervals properly

问题

我相对于React还很新手,刚刚开始一个基本项目,但我在尝试创建一个计数器应用时遇到了困难,自动增加和自动减少功能同时执行,导致计数器无法正常工作。任何帮助将不胜感激。提前感谢。

intervalId 是在组件全局范围内定义的变量。按钮点击处理程序如下所示:

const stopInterval = () => {
    clearInterval(intervalId);
    intervalId = null;
};
const handleAutoDecrement = () => {
    stopInterval();
    if (!intervalId) {
        intervalId = setInterval(() => {
            setCounter((prev) => prev - 1);
        }, 1000);
    }
};

const handleAutoIncrement = () => {
    stopInterval();
    if (!intervalId) {
        intervalId = setInterval(() => {
            setCounter((prev) => prev + 1);
        }, 1000);
    }
};  

我尝试在此之前在返回回调中清除了间隔,但结果相同,所以我完全不知道现在该怎么办。

英文:

I am fairly new to react and started out with a basic project but I'm struggling with a counter application that I am trying to make wherein the auto increment and the auto decrement function perform simultaneously so the count is not functioning properly. Any help would be appreciated. Thanks in advance.

intervalId is a variable that has been defined globally in the component. The button click handlers are as mentioned below.

const stopInterval = () => {
    clearInterval(intervalId);
    intervalId = null;
  };
 const handleAutoDecrement = () => {
    stopInterval();
    if (!intervalId) {
      intervalId = setInterval(() => {
        setCounter((prev) => prev - 1);
      }, 1000);
    }
  };

  const handleAutoIncrement = () => {
    stopInterval();
    if (!intervalId) {
      intervalId = setInterval(() => {
        setCounter((prev) => prev + 1);
      }, 1000);
    }
  };  

I tried clearing the intervals in a return call back prior to this but got the same result so I am completely clueless so as to do what now.

答案1

得分: 0

你正在将intervalId存储在本地变量中,每次重新渲染后其值都变为未定义。你需要将该值存储在状态中,以便在计数器值更改并重新渲染时,它能够保持intervalId的值。

import React, { useState } from 'react';
import './style.css';

function CounterComponent() {
  const [counter, setCounter] = useState(0);
  const [intervalId, setIntervalId] = useState();

  const stopInterval = () => {
    clearInterval(intervalId);
    setIntervalId(null);
  };

  const handleDecrement = () => {
    setCounter((prev) => prev - 1);
  };

  const handleAutoDecrement = () => {
    stopInterval();
    if (!intervalId) {
      const id = setInterval(() => {
        setCounter((prev) => prev - 1);
      }, 1000);
      setIntervalId(id);
    }
  };

  const handleAutoIncrement = () => {
    stopInterval();
    if (!intervalId) {
      const id = setInterval(() => {
        setCounter((prev) => prev + 1);
      }, 1000);
      setIntervalId(id);
    }
  };

  const handleIncrement = () => {
    setCounter((prev) => prev + 1);
  };

  return (
    <>
      <div className="counterClass">{counter}</div>
      <br />
      <br />
      <button onClick={handleDecrement} className="decrementButton">
        减少
      </button>
      <button onClick={handleAutoDecrement} className="autoDecrementButton">
        自动减少
      </button>
      <button onClick={handleAutoIncrement} className="autoIncrementButton">
        自动增加
      </button>
      <button onClick={handleIncrement} className="incrementButton">
        增加
      </button>
      <button onClick={stopInterval} className="incrementButton">
        停止
      </button>
    </>
  );
}

export default CounterComponent;
英文:

You are storing intervalId in local variable and after every re-render its value gets undefined. You will have to store the value in a state so that when counter value changes and it renders again it must persist the intervalId value.

import React, { useState } from &#39;react&#39;;
import &#39;./style.css&#39;;
function CounterComponent() {
const [counter, setCounter] = useState(0);
const [intervalId, setintervalId] = useState();
const stopInterval = () =&gt; {
clearInterval(intervalId);
setintervalId();
};
const handleDecrement = () =&gt; {
setCounter((prev) =&gt; prev - 1);
};
const handleAutoDecrement = () =&gt; {
stopInterval();
// if (!intervalId) {
setintervalId(setInterval(() =&gt; {
setCounter((prev) =&gt; prev - 1);
}, 1000));
console.log(&#39;interca&#39;, intervalId);
// }
};
const handleAutoIncrement = () =&gt; {
stopInterval();
// if (!intervalId) {
setintervalId(setInterval(() =&gt; {
setCounter((prev) =&gt; prev + 1);
}, 1000));
// }
};
const handleIncrement = () =&gt; {
setCounter((prev) =&gt; prev + 1);
};
return (
&lt;&gt;
&lt;div className=&quot;counterClass&quot;&gt;{counter}&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;button onClick={handleDecrement} className=&quot;decrementButton&quot;&gt;
Decrement
&lt;/button&gt;
&lt;button onClick={handleAutoDecrement} className=&quot;autoDecrementButton&quot;&gt;
AutoDecrement
&lt;/button&gt;
&lt;button onClick={handleAutoIncrement} className=&quot;autoIncrementButton&quot;&gt;
AutoIncrement
&lt;/button&gt;
&lt;button onClick={handleIncrement} className=&quot;incrementButton&quot;&gt;
Increment
&lt;/button&gt;
&lt;button onClick={stopInterval} className=&quot;incrementButton&quot;&gt;
Stop
&lt;/button&gt;
&lt;/&gt;
);
}
export default CounterComponent;

huangapple
  • 本文由 发表于 2023年1月6日 14:55:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75027851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定