问题描述
我有这样一个需求,我想在页面动态展示时间,也就是每秒更新
知识点储备
- react类组件写法
- react生命周期
- 如何获取时间:
new Date()
说明
因为我是借助react的,所以我把整个部分都写在App.jsx
中,再渲染到入口文件index.jsx
中的
代码实现
效果展示
App.jsx
import React, { Component } from 'react'
export default class App extends Component {
state = {
time:new Date().toTimeString().slice(0,8), // 第一步:初始化时间状态
};
componentDidMount() { // 第三步:组件的生命周期,挂载
this.tick();
}
componentWillUnmount() { // 第四步:组件将要被卸载时注意定时器必须清除
clearTimeout(this.timer);
}
tick = () => { // 第二步:设置时间间隔,更新时间
this.timer = setInterval(()=> { // 但是这样设计后,页面上的时间并不会实时修改,只会在每次刷新后修改
this.setState({ // 所以我们要借助生命周期函数:
time: new Date().toTimeString().slice(0,8),
})
}, 1000)
}
render() {
return (
<div>
<h1>现在是北京时间</h1>
<h2>{this.state.time}</h2>
</div>
)
}
}