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

使用react-native-countdown-component返回页面时报错:undefined is not a function

问题

使用react-native-countdown-component倒计时组件时,从其他页面返回当前页面会触发如下报错:

TypeError: undefined is not a function

移除该组件后页面运行正常,可确定问题源于此组件。组件使用代码如下:

return (
  <CountDown
    until={10}
    onFinish={() => alert('finished')}
    onPress={() => alert('hello')}
    size={20}
  />
)

可能的原因及解决办法

  • 组件未正确处理页面焦点变化
    该组件在页面跳转到后台时可能未暂停定时器,返回页面后尝试调用已失效的内部方法或访问undefined状态。可以通过监听页面焦点,手动重置倒计时:

    import { useFocusEffect } from '@react-navigation/native';
    import CountDown from 'react-native-countdown-component';
    import { useState, useCallback } from 'react';
    
    // 组件内部逻辑
    const [countdownTime, setCountdownTime] = useState(10);
    
    useFocusEffect(
      useCallback(() => {
        // 页面回到前台时重置倒计时
        setCountdownTime(10);
        return () => {
          // 可选:页面离开时做清理操作(若组件暴露相关方法)
        };
      }, [])
    );
    
    return (
      <CountDown
        until={countdownTime}
        onFinish={() => alert('finished')}
        onPress={() => alert('hello')}
        size={20}
      />
    );
    
  • 版本兼容性问题
    组件版本与当前React Native版本不兼容,导致页面返回时内部函数调用出错。尝试升级或降级至稳定版本:

    # 升级到最新版本
    npm install react-native-countdown-component@latest
    # 或降级到已知稳定版本
    npm install react-native-countdown-component@2.7.1
    
  • 回调函数上下文异常
    虽然使用了箭头函数,但组件内部处理回调时仍可能出现上下文丢失。尝试将回调函数提取为组件内独立函数:

    const handleCountdownFinish = () => alert('finished');
    const handleCountdownPress = () => alert('hello');
    
    return (
      <CountDown
        until={10}
        onFinish={handleCountdownFinish}
        onPress={handleCountdownPress}
        size={20}
      />
    );
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:35:24