我在使用 useState 和 useEffect Hook 时遇到问题
import { useState, useEffect } from "react";
const counter = ({ count, speed }) => {
const [inc, setInc] = useState(0);
useEffect(() => {
const counterInterval = setInterval(() => {
if(inc < count){
setInc(inc + 1);
}else{
clearInterval(counterInterval);
}
}, speed);
}, [count]);
return inc;
}
export default counter;
上面的代码是一个计数器组件,它在 props 中获取 count,然后用 0 初始化 inc 并递增它直到等于 count
问题是每次我得到 0 时,我都没有在 useEffect 和 setInterval 的回调中获取 inc 的更新值,因此它将 inc 呈现为 1 并且 setInterval 永远不会变得清晰。我认为 inc 必须关闭 use useEffect 和 setInterval 的回调,所以我必须在那里获取更新 inc,所以也许这是一个错误?
我无法在依赖项中传递 inc (这是在其他类似问题中建议的),因为在我的情况下,我已在 useEffect 中 setInterval 因此在依赖项数组中传递 inc 会导致无限循环
我有一个使用有状态组件的工作解决方案,但我想使用功能组件来实现此目的
请您参考如下方法:
有几个问题:
- 您没有从
useEffect返回函数清除间隔 - 您的
inc值不同步,因为您没有使用inc的先前值.
一个选项:
const counter = ({ count, speed }) => {
const [inc, setInc] = useState(0);
useEffect(() => {
const counterInterval = setInterval(() => {
setInc(inc => {
if(inc < count){
return inc + 1;
}else{
// Make sure to clear the interval in the else case, or
// it will keep running (even though you don't see it)
clearInterval(counterInterval);
return inc;
}
});
}, speed);
// Clear the interval every time `useEffect` runs
return () => clearInterval(counterInterval);
}, [count, speed]);
return inc;
}
另一个选项是包含 inc在 deps 数组中,这使事情变得更简单,因为您不需要使用之前的 inc里面setInc :
const counter = ({ count, speed }) => {
const [inc, setInc] = useState(0);
useEffect(() => {
const counterInterval = setInterval(() => {
if(inc < count){
return setInc(inc + 1);
}else{
// Make sure to clear your interval in the else case,
// or it will keep running (even though you don't see it)
clearInterval(counterInterval);
}
}, speed);
// Clear the interval every time `useEffect` runs
return () => clearInterval(counterInterval);
}, [count, speed, inc]);
return inc;
}
甚至还有更简单的第三种方法: 包括inc在 deps 数组中,如果 inc >= count ,早点回来再打电话setInterval :
const [inc, setInc] = useState(0);
useEffect(() => {
if (inc >= count) return;
const counterInterval = setInterval(() => {
setInc(inc + 1);
}, speed);
return () => clearInterval(counterInterval);
}, [count, speed, inc]);
return inc;






