代码之家  ›  专栏  ›  技术社区  ›  inoutwhy

react native显示当前时间并实时更新秒数

  •  30
  • inoutwhy  · 技术社区  · 8 年前

    我想像时钟一样在react原生应用程序中显示当前时间(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>
        );
    }
    
    8 回复  |  直到 8 年前
        1
  •  54
  •   Nguyên Hoàng    4 年前

    快走 setInterval 进入componentDidMount函数。

    这样地:

      componentDidMount() {
        setInterval(() => {
          this.setState({
            curTime : new Date().toLocaleString()
          })
        }, 1000)
      }
    

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

        2
  •  18
  •   Ilana Hakim    4 年前

    在react挂钩中,可以这样做:

    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);
    }, []);
    
        3
  •  15
  •   Kuhan    7 年前

    此方法工作良好,并显示 年月日时:年月日 总体安排

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

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

        4
  •  3
  •   Pang waqas ur Rehman    7 年前

    我得到了答案。下面的代码也可以工作。

    componentWillMount(){
        setInterval(function(){
            this.setState({
                curTime: new Date().toLocaleString()
            })
        }.bind(this), 1000);
    }
    
        5
  •  3
  •   nfroidure    6 年前

    我建议您使用 setTimeout 而不是 setInterval 事实上,浏览器可能会被繁重的处理过度控制,在这种情况下,您可能更希望不太频繁地更新时钟,而不是排队等待几次状态更新。

    具有 设置超时 当页面隐藏时,利用页面可见性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);
      }
    } 
    
        6
  •  0
  •   Ken Lee    4 年前

    完整代码如下:

    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>
        );
      }
    }
    
        7
  •  0
  •   Gustavo Barbosa    3 年前

    使用挂钩和力矩js:

    setInterval(() => {
      var date = moment().utcOffset("-03:00").format(" hh:mm:ss a");
      setCurrentDate(date);
    }, 1000);
    
        8
  •  0
  •   Codemaker2015    2 年前

    试试这个,

    import * as React from 'react';
    import { Text, View } from 'react-native';
    
    
    export default function App() {
      const [time, setTime] = React.useState();
    
      React.useEffect(() => {
        const timer = setInterval(() => {
          setTime(new Date().toLocaleString());
        }, 1000);
    
        return () => {
          clearInterval(timer);
        };
      }, []);
    
      return (
        <View>
          <Text>{time}</Text>
        </View>
      );
    }