import React, { Component } from "react";
export default class App extends Component {
state = {
currentTime:new Date().toLocaleString()
}
/**
* @author: xuehengfei
* @description: 当前时间
*/
getCurrentTime=() => {
this.setState(
{currentTime: new Date().toLocaleString()}
)
}
componentDidMount(){
this.interval=setInterval(() => this.getCurrentTime(), 1000)//组件挂载后才能插入定时器
}
componentWillUnmount() {
clearInterval(this.interval);//卸载组件时清除定时器
}
render() {
const {currentTime}=this.state
return (
<div className="container">
<div>现在的时间是:{currentTime}</div>
</div>
);
}
}
计时器需要放在钩子函数即componentDidMount,当组件卸载前需要销毁定时器。上述案例模拟的是一个当前时间的效果