我想在 react native 应用程序中像时钟一样显示当前时间(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>
);
}
最佳答案
只需将 setInterval
移至 componentDidMount 函数即可。
像这样:
componentDidMount() {
setInterval(() => {
this.setState({
curTime : new Date().toLocaleString()
})
}, 1000)
}
这将改变状态并每 1 秒更新一次。
关于reactjs - react native 显示当前时间并实时更新秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41294576/