英文:
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 "react";
import "./styles.css";
export default function App() {
const [info, setInfo] = useState({
title: "Current count",
count: 0
});
const stateUpdater = function () {
// 101 iterations
for (let i = 0; i <= 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 (
<div>
<h2>{info.title}:</h2>
{/* Count: This output should become 51 after clicking the button once */}
<div>{info.count}</div>
<button onClick={stateUpdater}>Run state updater</button>
</div>
);
}
答案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) => {
return {
count: prevState.count + 1
};
});
}
For more info go through this answer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论