[react] 怎么定时更新一个组件?
class Clock extends React.Component{
constructor(props){
super(props);
this.state={date:new Date()};
}
componentDidMount(){
this.timerID=setInterval(()=>this.tick(),1000);
}
componentWillUnmount(){
clearInterval(this.timerID);
}
tick(){
this.setState({
date:new Date()
});
}
render(){
return (
<div>
<h2>Timer {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
Creating a timer in componentDidMount, and recycle it in componentWillUnmount.
For react hooks, creating a timer in useEffect function with [] as the useEffect check condition which means this hook only runs on first render, and we can recycle the timer in useEffect callback function.
hooks 版
import React, { useState, useEffect } from 'react'
export default function TimerHooks () {
const [date, setDate] = useState(new Date())
useEffect(() => {
let timerId = setInterval(() => {
setDate(new Date())
}, 1000)
return () => {
clearInterval(timerId)
}
}, []);
return (
<div>
<p>时间: {date.toLocaleTimeString()}</p>
</div>
)
}
Most helpful comment
hooks 版