反应本地显示当前时间并实时更新秒数 [英] react native show current time and update the seconds in real-time

查看:79
本文介绍了反应本地显示当前时间并实时更新秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在反应本机应用程序中像时钟一样显示当前时间(MM / DD / YY hh:mm:ss),并每秒钟获取更新,我尝试使用new Date()并将其设置为状态,但是除非刷新页面,否则时间不会更新。
我也尝试过在render()中使用setInterval函数,它确实可以更新,但是对CPU来说却很昂贵。有没有好的方法可以实现该功能?

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don't update unless I refresh the page. I also tried using setInterval function in render(), it do got update but it's expensive for CPU. is there a good method to realise the function?

state = {
    curTime: null,
}
render(){
    setInterval(function(){this.setState({curTime: new  Date().toLocaleString()});}.bind(this), 1000);
    return (
        <View>
            <Text style={headerStyle.marginBottom15}>Date: {this.state.curTime}</Text>
        </View>
    );
}


推荐答案

只需移动 setInterval 进入componentDidMount函数。

Just move setInterval into componentDidMount function.

就像这样:

  componentDidMount() {
    setInterval(() => {
      this.setState({
        curTime : new Date().toLocaleString()
      })
    }, 1000)
  }

这将更改状态并每1秒更新一次。

This will change state and update every 1s.

这篇关于反应本地显示当前时间并实时更新秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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