首页 > 解决方案 > 在 React JS 中创建一个每秒更新的数字时钟 - 显示一些数字而不是时间

问题描述

我开始学习 ReactJS,作为示例项目的一部分,我必须创建一个每秒更新的数字时钟。下面是我的代码:

import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
    super(props);
    var currentTime = function () {
    return new Date().toLocaleTimeString();
    };
    this.state= {
        time: currentTime()
    }
}
render() {
    return (
        <div className="App">
            <h2>Sample Data: {this.state.time}</h2>
        </div>
    );
}
}

当我尝试上面的代码时,我得到了当前时间。因此,为了每秒更新时间,我更新了部分代码,如下所示

  constructor(props) {
      super(props);
      var currentTime = function () {
          return new Date().toLocaleTimeString();
      };
      this.state= {
          time: setInterval(currentTime(), 1000)
      }
  }

然后我的时间显示显示为“示例日期:2”。

我发现了一些类似的问题,但我发现这些问题的编码非常复杂。我要问的只是请让我知道我的代码有什么问题以及所需的任何代码更改。

提前非常感谢。

标签: reactjs

解决方案


您在上面的代码片段中所做的就是setTimeout在您的 state 属性中设置对的引用。

您希望每秒更新一次需要使用的状态componentDidMount,然后setState()像这样调用:

import React, { Component } from 'react';
export default class App extends Component {
this.interval = null;
currentTime() {
  return new Date().toLocaleTimeString();
};
constructor(props) {
    super(props);
    this.state= {
        time: this.currentTime()
    }
}
render() {
    return (
        <div className="App">
            <h2>Sample Data: {this.state.time}</h2>
        </div>
    );
}
componentDidMount() {
  this.interval = setInterval(() => this.setState({time: this.currentTime()}), 1000)
}

componentWillUnMount(){
  clearInterval(this.interval);
}
}

每当启动间隔或事件侦听器时,在组件卸载之前清除它是很重要的,否则会出现内存泄漏。


推荐阅读