Nextjs:更新状态在时间间隔内不工作

这是我的状态:

const [time, setTime] = useState(10)

这是我的处理程序:

const runTimer = () => {
    useEffect(() => {
        const interval = setInterval(() => {
            console.log(time)
            if (time > 0) {
                setTime(time - 1)
            } else {
                console.log("End")
            }
        }, 1000);
        return () => clearInterval(interval)
    }, [])
}

我的日志:

9
9
9
9
9
.
.
.

为什么setTime不起作用?

time每1000个延迟增加最多的变量


解决方案

您传递给useEffect的函数具有closed over该组件第一次呈现时的timer变量。

每次呈现组件时,都会读取状态的当前值,并使用该值创建timer变量。

不过,您并没有访问该变量。您正在访问的variable间隔不会改变,因此每次您访问它时,它仍然是10


将当前值作为参数传递给状态函数,因此请改用当前值。

const Timer = () => {
    const [timer, setTime] = useState(10);
    useEffect(() => {
        const interval = setInterval(() => {
            setTime(
                (currentTime) => {
                    if (currentTime > 0) {
                        return currentTime - 1;
                    } else {
                        console.log(end);
                        clearInterval(interval);
                        return currentTime;
                    }
                }
            );
        }, 1000);
        return () => clearInterval(interval)
    }, [])
    return <p>{timer}</p>
}

相关文章