You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中useEffect倒计时组件仅执行一次的问题排查

React Native Redux倒计时组件停止问题修复

你的倒计时组件初始值为7,减到6后就停住,核心原因是控制倒计时的useEffect依赖项不完整:

这个useEffect只监听了dispatch,但当currentCount、isCountdownFinished、isCountdownCancelled这些关键状态变化时,它不会重新执行。第一次执行时,currentCount为7,触发定时器把数值减到6;但状态更新后,useEffect没有再次运行,自然不会触发下一轮倒计时逻辑。

修复方案

1. 补全useEffect依赖项并添加定时器清理

修改第二个useEffect,把所有用到的状态和函数都加入依赖数组,同时添加清理函数避免内存泄漏:

useEffect(() => {
    if(isCountdownFinished) {
        handleFinishedCountdown()
    } else if(isCountdownCancelled){
        handleCancelledCountdown()
    } else {
        const timer = setTimeout(() => {
            dispatch(reduceCurrentCountByOne())
        }, 1000);
        // 组件卸载或状态更新时清理上一个定时器
        return () => clearTimeout(timer);
    }
}, [dispatch, currentCount, isCountdownFinished, isCountdownCancelled, handleFinishedCountdown, handleCancelledCountdown])

2. 用useCallback稳定函数引用

为了避免handleFinishedCountdown和handleCancelledCountdown每次渲染都生成新实例,导致useEffect不必要重复执行,用useCallback包裹这两个函数:

import { useCallback } from 'react';

// ...

const handleCancelledCountdown = useCallback(() => {
    // 你的业务逻辑
}, []);

const handleFinishedCountdown = useCallback(() => {
    // 你的业务逻辑
}, []);

为什么之前的修改无效?

你调整初始值、替换按钮组件、用requestAnimationFrame包裹setTimeout这些操作,都没触及到「useEffect依赖项不全导致无法重新触发」这个核心问题,所以无法解决倒计时停止的问题。

内容的提问来源于stack exchange,提问作者Alan Jurado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:15:04