-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
避免陷入闭包陷阱
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>
)
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels