在React以前的版本中,各类生命周期函数的提供,在给我们灵活的操作组件带来便利的同时,也造成了某些生命周期函数利用率低,代码冗余的现象,所以在后来的版本中,基于函数式组件React提供了React Hook的操作,使得函数是组件更加灵活,下面就是利用useEffect来实现的一个计时器效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, {useState,useEffect} from 'react';

let timeChange; //声明定时器

const Timer = () => {
const [current, setCurrent] = useState(0); // timer
const [time, setTime] = useState(5); // timer
useEffect(() => {
clearInterval(timeChange)
}, [])
useEffect(() => {
console.log(current)
if(current === 1) runTimerJump()
}, [current])
useEffect(() => {
if(time === 0){
clearInterval(timeChange)
setTime(5)
console.log('倒计时完毕!')
}
}, [time])
const runTimerJump = () => {
timeChange = setInterval(() => setTime(t => --t), 1000)
}

return (
<>
<p>
<span>{time}s 后执行对应的操作</span>
<br />
</p>
<p><button onClick={()=>setCurrent(1)}>点击开启</button></p>
</>
)
}

export default Timer