React Hook 定时器
前段时间学习了 React 新发布的 Hook 新功能,学完立马就爱上了这个新 API,用起来感觉比 class 组件爽多了。但 hook 虽然看似简单,但是要能熟练运用还是得花上一段时间。
随机间隔计数器
目标:实现一个计数器,通过输入框输入计数器每次计数的时间(ms),按输入的时间间隔每次增一
class 版本
如果熟悉 React class 组件模式,这个功能实现不难。但是这样有两个弊端:
- 会有大量模板代码,我们不得不通过多个生命周期来实现一个功能
- 同一个功能逻辑代码却分布在不同地方,比如创建定时器和清除定时器放在两个不同的生命周期
import React from 'react'
class ClassVersion extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0,
delay: 1000
}
}
componentDidMount() {
this.timer = setInterval(this.tick, this.state.delay)
}
componentDidUpdate(prevProps, prevState) {
if (prevState.delay !== this.state.delay) {
clearInterval(this.timer)
this.timer = setInterval(this.tick, this.state.delay)
}
}
componentWillUnmount() {
clearInterval(