我想像时钟一样在本机应用程序中显示当前时间(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>
);
}
原文由 inoutwhy 发布,翻译遵循 CC BY-SA 4.0 许可协议
只需将
setInterval
移动到 componentDidMount 函数中。像这样 :
这将改变状态并每 1 秒更新一次。