有两种方式仅供参考
// 第一种方式
import { useEffect, useState } from 'react'
const HelloWorld = () => {
const [count, setCount] = useState(0)
useEffect(() => {
const timer = setInterval(() => {
setCount(pre => pre + 1)
}, 1000)
return () => clearInterval(timer)
}, [])
return <p>{count}</p>
}
export default HelloWorld
// 第二种方式不推荐
// 首先 eslint 会提示把 count 当做依赖项
// 其次会频繁调用创建定时器和销毁定时器,但是也可用
import { useEffect, useState } from 'react'
const HelloWorld = () => {
const [count, setCount] = useState(0)
useEffect(() => {
const timer = setInterval(() => {
setCount(count + 1)
}, 1000)
return () => clearInterval(timer)
}, [count])
return <p>{count}</p>
}