ReactJS 使用 for 循环和事件处理停止计数器达到特定限制。

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

ReactJS Stop the counter at certain limit using for loop and eventHandling

问题

我有以下的JSX代码,我想要在计数器达到51时停止它。计数器只应该在事件触发后开始,并且应该一直调用,直到达到51。

我尝试使用useEffect,但它无法停止计数器。

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [info, setInfo] = useState({
    title: "当前计数",
    count: 0
  });

  const stateUpdater = function () {
    // 101次迭代
    for (let i = 0; i <= 100; i++) {
      // 只有偶数
      // 在0和101之间共有51个偶数
      if (i % 2 === 0) {
        setInfo({ count: info.count + 1 });
      }
    }
  };

  return (
    <div>
      <h2>{info.title}:</h2>

      {/* 计数:点击按钮后应该变为51 */}
      <div>{info.count}</div>

      <button onClick={stateUpdater}>运行状态更新器</button>
    </div>
  );
}
英文:

I have the following JSX code and I want to stop the counter once it reaches 51. The counter should start only once the event is triggered and it should make a continuous call until it reaches 51.

I tried using useEffect but it won't stop the counter.

import { useState } from &quot;react&quot;;
import &quot;./styles.css&quot;;

export default function App() {
  const [info, setInfo] = useState({
    title: &quot;Current count&quot;,
    count: 0
  });

  const stateUpdater = function () {
    // 101 iterations
    for (let i = 0; i &lt;= 100; i++) {
      // Only even numbers
      // There are a total of 51 even numbers in between 0 and 101
      if (i % 2 === 0) {
        setInfo({ count: info.count + 1 });
      }
    }
  };

  return (
    &lt;div&gt;
      &lt;h2&gt;{info.title}:&lt;/h2&gt;

      {/* Count: This output should become 51 after clicking the button once */}
      &lt;div&gt;{info.count}&lt;/div&gt;

      &lt;button onClick={stateUpdater}&gt;Run state updater&lt;/button&gt;
    &lt;/div&gt;
  );
}

答案1

得分: 0

从React文档中:
> React可能会将多个setState()(在这种情况下是useState的set方法)调用批处理成单个更新以提高性能。因为this.props和this.state可能会异步更新,所以不应该依赖它们的值来计算下一个状态。
>
>要修复这个问题,使用一个接受函数而不是对象的第二种形式的setState()。该函数将接收前一个状态作为第一个参数,并在应用更新时的props作为第二个参数。

修复方法:

if (i % 2 === 0) {
   setInfo((prevState) => {
     return {
       count: prevState.count + 1
     };
   });
}

更多信息请参阅此答案

英文:

From the react docs:
> React may batch multiple setState() (in this case set method of
> useState) calls into a single update for performance. Because
> this.props and this.state may be updated asynchronously, you should
> not rely on their values for calculating the next state.
>
>To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument

The fix:

if (i % 2 === 0) {
   setInfo((prevState) =&gt; {
     return {
       count: prevState.count + 1
     };
   });
}

For more info go through this answer.

huangapple
  • 本文由 发表于 2023年6月15日 15:26:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480075.html
匿名

发表评论

匿名网友

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

确定