小编典典

反应本地显示当前时间并实时更新秒数

reactjs

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

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>
    );
}

阅读 434

收藏
2020-07-22

共1个答案

小编典典

只需setInterval进入componentDidMount函数即可。

像这样 :

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

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

2020-07-22