Skip to content

React 自定义 hook 实现验证码倒计时 #2

@heycn

Description

@heycn

避免陷入闭包陷阱

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>
  )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions