我一直在玩 React 并有以下时间组件,它只将 Date.now()
呈现到屏幕上:
import React, { Component } from 'react';
class TimeComponent extends Component {
constructor(props){
super(props);
this.state = { time: Date.now() };
}
render(){
return(
<div> { this.state.time } </div>
);
}
componentDidMount() {
console.log("TimeComponent Mounted...")
}
}
export default TimeComponent;
让这个组件每秒更新一次以从 React 的 Angular 重新绘制时间的最佳方法是什么?
最佳答案
你需要使用setInterval
来触发变化,但是你也需要在组件卸载时清除定时器,以防止它留下错误和内存泄漏:
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
关于javascript - 每秒更新一次 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39426083/