Reactjs 在React JS中创建一个每秒更新一次的数字时钟-显示一些数字而不是时间

Reactjs 在React JS中创建一个每秒更新一次的数字时钟-显示一些数字而不是时间,reactjs,Reactjs,我开始学习ReactJS,作为示例项目的一部分,我必须创建一个每秒更新的数字时钟。下面是我的代码: import React, { Component } from 'react'; export default class App extends Component { constructor(props) { super(props); var currentTime = function () { return new Date().toLocaleTimeStri

我开始学习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>
    );
}
}
然后我的时间显示为“示例日期:2”

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


事先多谢

您在上述代码段中所做的是在您的状态属性中将引用设置为
setTimeout

需要使用
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);
}
}
import React,{Component}来自'React';
导出默认类应用程序扩展组件{
this.interval=null;
当前时间(){
返回新日期();
};
建造师(道具){
超级(道具);
此。状态={
时间:this.currentTime()
}
}
render(){
返回(
示例数据:{this.state.time}
);
}
componentDidMount(){
this.interval=setInterval(()=>this.setState({time:this.currentTime()}),1000)
}
组件将卸载(){
clearInterval(这个.interval);
}
}
无论何时启动interval或event listener,在卸载组件之前清除它都很重要,否则将出现内存泄漏

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