setInterval in a React app

前端 未结 7 538
天涯浪人
天涯浪人 2020-11-30 20:46

I\'m still fairly new at React, but I\'ve been grinding along slowly and I\'ve encountered something I\'m stuck on.

I am trying to build a \"timer\" component in Re

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 21:19

    Manage setInterval with React Hooks:

      const [seconds, setSeconds] = useState(0)
    
      const interval = useRef(null)
    
      useEffect(() => { if (seconds === 60) stopCounter() }, [seconds])
    
      const startCounter = () => interval.current = setInterval(() => {
        setSeconds(prevState => prevState + 1)
      }, 1000)
    
      const stopCounter = () => clearInterval(interval.current)
    

提交回复
热议问题