We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
避免陷入闭包陷阱
import React, {useEffect, useState} from 'react' const useCountDown = second => { const [seconds, setSeconds] = useState(second) useEffect(() => { setTimeout(() => { if (seconds > 0) { setSeconds(seconds - 1) } }, 1000) }, [seconds]) return [seconds, setSeconds] } const App = () => { const [seconds, setSeconds] = useCountDown(0) return ( <button disabled={seconds !== 0} onClick={() => setSeconds(60)}> {seconds > 0 ? `${seconds}s后可点击` : '点击开始倒计时'} </button> ) }
The text was updated successfully, but these errors were encountered:
如果你想严格地控制 Timer 的执行次数,请使用使用 useRef + clearInterval,并且在 useEffect 中的 return => {} 里调用
Timer
useRef
clearInterval
useEffect
return => {}
import { useEffect, useRef, useState } from 'react' type CountDown = (second: number) => [number, (seconds: number) => void] export const useCountDown: CountDown = second => { const [seconds, setSeconds] = useState(second) const timer = useRef<number>() useEffect(() => { if (seconds > 0) { timer.current = window.setTimeout(() => { console.log('update') setSeconds(seconds - 1) }, 1000) } return () => window.clearInterval(timer.current) }, [seconds]) return [seconds, setSeconds] }
Sorry, something went wrong.
No branches or pull requests
The text was updated successfully, but these errors were encountered: