反应原生显示当前时间并实时更新秒数

ino*_*why 11 timer clock reactjs react-native

我想在响应原生应用程序(如时钟)中显示当前时间(MM/DD/YY hh:mm:ss),并且每秒都获得更新,我尝试使用新的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>
    );
}
Run Code Online (Sandbox Code Playgroud)

Ngu*_*àng 29

只需setInterval进入componentDidMount函数即可.

像这样 :

  componentDidMount() {
    setInterval( () => {
      this.setState({
        curTime : new Date().toLocaleString()
      })
    },1000)
  }
Run Code Online (Sandbox Code Playgroud)

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

我在RNPlayground中做了一个简单的例子.看看: 这里


小智 14

在反应钩子中,它可以像这样完成:

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);
}, []);
Run Code Online (Sandbox Code Playgroud)


小智 11

此方法工作正常,并显示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>
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)

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