import { useEffect, useState, useRef } from 'react'
import { Link, useHistory } from 'react-router-dom'
import styles from './index.module.scss'
const NotFound = () => {
const [count, setCount] = useState(5)
const timeRef = useRef(null)
const history = useHistory()
useEffect(() => {
timeRef.current = setInterval(() => {
setCount(preCount => preCount - 1)
}, 1000);
//因为依赖项为空数组,所以,该返回的清理函数只会在组件卸载时执行
return () => {
//退出组件时卸载定时器
clearInterval(timeRef.current)
}
}, [])
//count 必须写在另一个useEffect中,不然定时器会越开越多,出现不可控的后果
useEffect(() => {
if (count === 0) {
history.replace('/home')
}
}, [count, history])
return <div className={styles.root}>
<h1>您访问的页面不存在哟~</h1>
<p>将在{count}秒后返回首页(或者<Link to="/home">点击立即返回首页</Link> )</p>
</div>
}
export default NotFound
react中hook怎么使用倒计时
最新推荐文章于 2025-01-10 11:13:19 发布