react實現定時器
阿新 • • 發佈:2019-02-06
class Timer extends Component { state = { seconds: 0 } tick = () => { const { seconds } = this.state; this.setState({ seconds: seconds + 1 }) } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <div>Seconds:{this.state.seconds}</div> ) } } export default Timer;