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

前端 未结 6 1831
说谎
说谎 2021-02-05 05:53

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don

6条回答
  •  礼貌的吻别
    2021-02-05 06:28

    This method works fine and displays MM/DD/YY hh:mm:ss format

    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 (
              

    The time is {this.state.time}.

    ); } }

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

提交回复
热议问题