我想在react native应用程序中像时钟一样显示当前时间(MM/DD/YY hh:MM:ss),并每秒钟更新一次,我try 使用new Date()并将其设置为状态,但除非刷新页面,否则时间不会更新.

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

这将改变状态并每1s更新一次.

React-native相关问答推荐

文本输入提示

Appcenter codepush 返回请求被阻止

如何在react native 中将选定的自定义复选框数据发送到下一页?

React Native Ios错误 - ENOENT:no such file or directory, uv_cwd (null)

React Native - Expo:fontFamily 'SimpleLineIcons' 不是系统字体,尚未通过 Font.loadAsync 加载

按下按钮有一个borderRadius

如何停止在 textInput React Native 中输入空格?

混合 JavaScript 移动开发 - Apache Cordova vs Capacitor with Ionic vs NativeScript vs React Native

由于依赖关系,在 run-android 上构建失败

如何清除react-native webview cookie?

Undefined 不是判断 this.state.* 的对象

React Native localhost 另一个调试器已经连接

TouchableHighlight onPress 不起作用

如何将 View 定位在 ScrollView 的底部?

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.

react-native fetch() cookie 持久化

如何在 Expo 和 React Native 中使用绝对路径导入?

使用 expo SDK react-native ios 应用程序的 Info.plist 文件

React Native font outline / textShadow

无法在react-native中分配给# 的只读属性props