英文:
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);
};
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论