首页 文章

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

提问于
浏览
7

我想在响应原生应用程序(如时钟)中显示当前时间(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>
    );
}

4 回答

  • 3

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

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

    我建议更喜欢使用 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);
      }
    }
    
  • 5

    只需将 setInterval 移动到componentDidMount函数中即可 .

    像这样 :

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

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

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

  • 14

    此方法工作正常并显示 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>
            );
          }
        }
    

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

相关问题