reactjs - 在 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”。
我发现了一些类似的问题,但我发现这些问题的编码非常复杂。我要问的只是请让我知道我的代码有什么问题以及所需的任何代码更改。
提前非常感谢。
解决方案
您在上面的代码片段中所做的就是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);
}
}
每当启动间隔或事件侦听器时,在组件卸载之前清除它是很重要的,否则会出现内存泄漏。
推荐阅读
- javascript - TypeError:无法在节点js中设置未定义的属性'18dit075'
- postgresql - PostgreSQL 从一个日期列构建工作范围
- python - 在 Python 中理解 super
- flutter - Flutter - 字符串变量中的 HTML 命令
- python - 从生成器对象python返回值
- javascript - Mongo 通过 subdoc 数组的总和查找
- scheme - 如何分析呼叫/抄送中的等效接收者?
- sql - 查询表达式 SUM 中缺少运算符的语法错误
- c - C 2darray 值意外更改
- php - 如何根据 PHP 中的公共键值对对对象进行分组?