在React中使用date-fns库时如何实现时间自动刷新
解决方案
你的代码存在两个核心问题导致时间无法自动更新:
- constructor仅会在组件实例初始化时执行一次,因此当前时间只会在组件第一次加载时计算一次,后续没有触发重新计算的逻辑
- 组件外部的
setInterval(Time, 60000)写法无效,传入类组件不会触发状态更新,同时定时器没有和组件生命周期绑定,还会有内存泄漏风险
修复后的完整类组件代码
import { Component } from 'react'; import { format } from 'date-fns'; export class Time extends Component { constructor() { super(); const today = new Date(); const time = format(today, 'HH:mm'); this.state = { currentTime: time } } componentDidMount() { // 组件挂载后启动定时器,每60秒更新一次时间 this.updateTimer = setInterval(() => { const now = new Date(); const newTime = format(now, 'HH:mm'); this.setState({ currentTime: newTime }); }, 60000); } componentWillUnmount() { // 组件卸载时清除定时器,避免内存泄漏 clearInterval(this.updateTimer); } render() { return ( <div className="time"> <p> My Local Time is { this.state.currentTime } GMT +3 </p> </div> ); } }
以上代码直接删除原组件外部无效的setInterval即可使用。
内容的提问来源于stack exchange,提问作者damian-sketch
相关产品推荐
相关产品推荐

