React Hooks Interval

示例代码

import React, { useState, useEffect } from 'react';

function Count() {
  const [countSec, setCountSec] = useState(0);

  useEffect(() => {
    if (countSec) {
      const id = setTimeout(() => {
        setCountSec(countSec - 1);
      }, 1000);
      return () => clearTimeout(id);
    }
  }, [countSec]);

  return (
    <button onClick={() => setCountSec(60)}>
      {
        !countSec ? 'start count' : countSec
      }
    </button>
  );
}

export default Count;