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

react native show current time and update the seconds in real-time

我想像时钟一样在本机应用程序中显示当前时间(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 秒更新一次。

我得到了答案。下面的代码也有效。

componentWillMount(){
    setInterval(function(){
        this.setState({
            curTime: new Date().toLocaleString()
        })
    }.bind(this), 1000);
}

此方法工作正常并显示 MM/DD/YY hh:mm:ss 格式

class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          time: new Date().toLocaleString()
        };
      }
      componentDidMount() {
        this.intervalID = setInterval(
          () => this.tick(),
          1000
        );
      }
      componentWillUnmount() {
        clearInterval(this.intervalID);
      }
      tick() {
        this.setState({
          time: new Date().toLocaleString()
        });
      }
      render() {
        return (
          <p className="App-clock">
            The time is {this.state.time}.
          </p>
        );
      }
    }

原始 link : https://openclassrooms.com/courses/build-web-apps-with-reactjs/build-a-ticking-clock-component

我建议更喜欢使用 setTimeout 而不是 setInterval,事实上,浏览器可能会因繁重的处理而不堪重负,在这种情况下,您可能更愿意较少地更新时钟而不是排队状态的几个更新。

使用 setTimeout 时,利用页面可见性 API 可以更轻松地在页面隐藏时完全停止计时(参见 https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API)。

export default class MyClock {
  constructor(props) {
    super(props);

    this.state = {
      currentTime: Date.now(),
    }; 
  }

  updateCurrentTime() {
    this.setState(state => ({
      ...state,
      currentTime: Date.now(),
    }));
    this.timeoutId = setTimeout(this.updateCurrentTime.bind(this), 1000);
  }

  componentWillMount() {
    this.updateCurrentTime();
    document.addEventListener('visibilitychange', () => {
      if(document.hidden) {
        clearTimeout(this.timeoutId);
      } else {
        this.updateCurrentTime();
      }
    }, false);
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId);
  }
} 

完整代码在这里:

import React, { Component } from 'react';
import { Text, View } from 'react-native';


export default class KenTest extends Component {

  componentDidMount(){ 

    setInterval(() => (

      this.setState(
        { curTime : new Date().toLocaleString()}

      )
    ), 1000);
  }


state = {curTime:new Date().toLocaleString()};


  render() {
    return (
      <View>
  <Text>{'\n'}{'\n'}{'\n'}The time is: {this.state.curTime}</Text>

      </View>
    );
  }
}

在react hooks中,可以这样做:

import React, { useState, useEffect } from "react";

const [dt, setDt] = useState(new Date().toLocaleString());

useEffect(() => {
    let secTimer = setInterval( () => {
      setDt(new Date().toLocaleString())
    },1000)

    return () => clearInterval(secTimer);
}, []);

使用钩子和 moment-js:

setInterval(() => {
  var date = moment().utcOffset("-03:00").format(" hh:mm:ss a");
  setCurrentDate(date);
}, 1000);