使用es6使用react native创建计时器 [英] create timer with react native using es6

查看:48
本文介绍了使用es6使用react native创建计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我的应用程序中添加一个计时器,该计时器是使用react native构建的.

I am looking to add a timer to my app which is built using react native.

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

I have looked at the link to the timer mixin in the documentation however I have built the rest of the app using es6 so this won't be compatible.

我尝试了以下方法.

在我的主类中,我有一个名为 getTimerCountDown

In my Main class I have a function called getTimerCountDown

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

getTimeRem() {
    return this.state.timeRemaining;
}

我尝试在 componentDidUpdate 中调用它,如下所示.如果不与UI进行任何其他交互,则可以按我的意愿进行操作.

I have tried calling this in componentDidUpdate as shown below. This works as I want it to if I don't make any other interactions with the UI.

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

If I do (eg I have a button I can click on the view.) as `componentDidUpdate gets called again the conunter gets really quick (as it is getting called x number of times)

componentDidUpdate(){
    this.getTimerCountDown();
}

我不确定我是否完全按照错误的方向做,还是对我所做的事情进行小的改动都能使我得到想要的东西.使用ES6在本机反应中使倒数计时器工作的最佳方法是什么?

I am not sure if I am completly on the wrong track here or a small change to what I have done can get me what I want. What is the best way to get a countdown timer working in react native using es6?

计时器类在主页上

<Timer timeRem={this.getTimeRem()} />

返回

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

推荐答案

即使在没有任何其他UI交互的情况下,我也不十分确定该如何工作.每次重新渲染组件时,都会调用 componentDidUpdate ,这是在内部状态或传递的道具发生更改时发生的.没有什么可以指望每秒钟发生的事情.

I'm not really sure how that would work even without any other UI interactions. componentDidUpdate is called every time the component is re-rendered, something that happens when the internal state or passed down props have changed. Not something you can count on to happen exactly every second.

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

How about moving the getTimerCountDown to your componentDidMount method (which is only called once), and then using setInterval instead of setTimeout to make sure the counter is decremented continuously?

这篇关于使用es6使用react native创建计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆