File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -38,11 +38,11 @@ const el = (
3838
3939 { /* <RefLoseControl /> */ }
4040 < Modal >
41- < CountDown time = { 5 } />
41+ < CountDown time = { 5 } interval = { 600 } />
4242 </ Modal >
4343
4444 < This />
45- < Num />
45+ { /* <Num/> */ }
4646 </ >
4747)
4848
Original file line number Diff line number Diff line change 11import React , { useEffect , useState , useRef } from 'react'
22
33export default function ( props ) {
4- const [ time , setTime ] = useState ( props . time )
4+ const { time : initialTime , interval = 1000 } = props
5+ const [ time , setTime ] = useState ( initialTime )
56
67 // 1
78 const timerRef = useRef ( null )
89 useEffect ( ( ) => {
910 timerRef . current = setInterval ( ( ) => {
10- setTime ( pre => pre - 1 )
11- } , 1000 )
11+ setTime ( pre => pre - interval / 1000 )
12+ } , interval )
1213 // 提前卸载
1314 return ( ) => clearInterval ( timerRef . current )
14- } , [ ] )
15+ } , [ interval ] )
1516 useEffect ( ( ) => {
16- if ( time <= 0 ) {
17+ const nextTime = time - interval / 1000
18+ if ( nextTime <= 0 ) {
1719 // 倒计时结束卸载
1820 clearInterval ( timerRef . current )
1921 }
2022 } , [ time ] )
2123
2224 // 2
2325 useEffect ( ( ) => {
24- if ( time <= 0 ) return
25- const id = setTimeout ( ( ) => setTime ( time - 1 ) , 1000 )
26+ const nextTime = time - interval / 1000
27+ if ( nextTime <= 0 ) return // 先判断,确保不会显示负的
28+ const id = setTimeout ( ( ) => setTime ( Math . max ( 0 , nextTime ) ) , interval )
29+ // 或者通过 max 确保显示到 0 为止
2630 return ( ) => clearTimeout ( id ) // 清理
27- } , [ time ] )
31+ } , [ time , interval ] )
2832
2933 return (
3034 < div >
You can’t perform that action at this time.
0 commit comments