使用es6创建使用react native的计时器

ak8*_*k85 10 javascript facebook ios reactjs react-native

我希望为我的应用程序添加一个计时器,它使用react native.

我已经查看了文档中的计时器mixin的链接,但是我使用es6构建了应用程序的其余部分,因此这将不兼容.

我试过以下.

在我的Main类中,我有一个名为的函数 getTimerCountDown

getTimerCountDown() {
    setTimeout(() => {
      this.setTimeRemaining(this.getTimeRem()-1);
    }, 1000);
}

getTimeRem() {
    return this.state.timeRemaining;
}
Run Code Online (Sandbox Code Playgroud)

我试过调用它,componentDidUpdate如下所示.如果我不与UI进行任何其他交互,这就像我想要的那样.

如果我这样做(例如,我有一个按钮,我可以点击视图.)当`componentDidUpdate被再次调用时,conunter变得非常快(因为它被称为x次)

componentDidUpdate(){
    this.getTimerCountDown();
}
Run Code Online (Sandbox Code Playgroud)

我不确定我是否完全走错了轨道,或者对我所做的一些小改动可以得到我想要的东西.使用es6让倒数计时器在本机中工作的最佳方法是什么?

主页上的计时器类

<Timer timeRem={this.getTimeRem()} />
Run Code Online (Sandbox Code Playgroud)

回报

render(){
    return (
        <View style={styles.container}>
            <Text> This is the Timer : {this.props.setTimer}  - {this.props.timeRem} </Text>
        </View>
    )
}
Run Code Online (Sandbox Code Playgroud)

tke*_*ers 5

我真的不确定即使没有任何其他UI交互也将如何工作。componentDidUpdate每次重新渲染组件时都会调用,这是在内部状态或传递的props更改时发生的。您无法指望每秒钟都会发生的事情。

如何将getTimerCountDown移至您的componentDidMount方法(仅调用一次),然后使用setInterval而不是setTimeout确保计数器连续递减?