【问题标题】:Using react-native-background-timer使用 react-native-background-timer
【发布时间】:2019-02-18 10:51:12
【问题描述】:

我正在构建一个简单的 Android 应用程序。我现在正试图让我的手机每 3 秒振动一次。这是我的代码:

componentDidMount() {
    BackgroundTimer.runBackgroundTimer(() => {
        Vibration.vibrate(1000);
    }, 3000);
}

componentWillUnmount() {
    BackgroundTimer.stopBackgroundTimer();
}

render() {
    return (
        <View style={styles.container}>
            <ScrollView>
                {this.state.errors.map(e => {
                    const {error, solved, errorInfo, key, uid, date} = e;
                    return (
                        <View key={e.key} style={{backgroundColor: solved === true ? 'green' : '#ff5b68'}}>
                            <Text>{error}</Text>
                            <Text>{errorInfo}</Text>
                            <Text>{key}</Text>
                            <Text>{uid}</Text>
                            <Text>{date}</Text>
                            <MarkedAsSolvedButton id={key} solved={solved}/>
                        </View>
                    )
                })}
            </ScrollView>
        </View>
    );
}

但我收到一个错误:

TypeError: TypeError: undefined is not an object (evalating 'RNBackgroundTimer.start')

我错过了什么?

我正在使用这个模块:https://github.com/ocetnik/react-native-background-timer

【问题讨论】:

  • 你运行 react-native 链接了吗?
  • 如果你在 ios 上测试它,那么请检查 pod!
  • 我确实链接了它。我正在 Android 上测试它
  • 然后检查 build.gradle 看看是否包含实现和项目链接?请在你的原生安卓代码中
  • 我以前从未从事过 Android 开发工作。我在找什么?

标签: android react-native


【解决方案1】:

您可以使用 clearInterval 方法。首先声明一个全局变量,方便启动和结束定时器。示例代码如下:

let myTimer;
class ABC extends React.Component {
componentDidMount()
{
myTimer = BackgroundTimer.setInterval(()=> {
// Your repeated task here.
}, 3000);
}
componentWillUnMount()
{
  // Code to stop timer.
 BackgroundTimer.clearInterval(myTimer);
}
render() {
// remaining code
 }
}

【讨论】:

    【解决方案2】:

    我想组件在使用之前需要先启动。首先调用 BackgroundTimer.start() 然后尝试你的逻辑。

    【讨论】:

    • 你认为我应该在哪里添加它?
    • 关于 componentDidMount() 方法
    • 你在使用 create-react-native-app 吗?如果是这样,根据文档,在运行 react-native 链接之前将其弹出。
    • 我正在使用世博会。我之前确实弹出过它
    • 链接包时一定有问题。确保包在 MainApplication 和 settings.gradle 中正确链接。这个链接可能对你有用github.com/ocetnik/react-native-background-timer/issues/35
    猜你喜欢
    • 1970-01-01
    • 2022-12-30
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多