在React.js中在特定点重置计数器。

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

Resetting a Counter at a Certain Point in React.js

问题

以下是已经翻译好的部分:

我正在尝试调整这段代码,以便在计数达到一定点时重置,比如说20。我在react.js中找到最佳方法感到困难。下面是我正在使用的代码:

const [position, setPosition] = useState(0);

useEffect(() => {
  const id = setInterval(() => setPosition((oldPosition) => oldPosition + 1), 10);

  return () => {
    clearInterval(id);
  };
}, []);

任何帮助将不胜感激!

英文:

I am trying to adjust this code so that it resets when the count reaches a certain point, say 20. I'm struggling to determine the best way to go about this in react.js. Below is the code that I'm working with

const [position, setPosition] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setPosition((oldPosition) => oldPosition + 1), 10);

    return () => {
      clearInterval(id);
    };
  }, []);

Any help is much appreciated!

答案1

得分: 1

检查 setPosition 回调中的 oldPosition,如果它等于或大于 20,那么执行 clearInterval setState 回调参数将始终更新为最新值)

const [position, setPosition] = useState(0);

useEffect(() => {
  const id = setInterval(() => setPosition((oldPosition) => {
    if (oldPosition >= 20) {
       clearInterval(id);
       return oldPosition;
    }
    return oldPosition + 1
  }), 10);

  return () => {
    clearInterval(id);
  };
}, []);
英文:

Check the oldPosition inside setPosition callback, if it equals or more than 20, then clearInterval ( setState callback parameter will always be updated with the latest value )

const [position, setPosition] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setPosition((oldPosition) => {
      if (oldPosition >= 20) {
         clearInterval(id);
         return oldPosition;
      }
      return oldPosition + 1
    }), 10);

    return () => {
      clearInterval(id);
    };
  }, []);

huangapple
  • 本文由 发表于 2023年2月24日 04:42:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550116.html
匿名

发表评论

匿名网友

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

确定