react-hooks的页面设置定时器

hooks页面设置定时器

在hooks中设置定时器时,设置变量储存定时器时最后用:const [timer, setTimer] = useState(null); 这样方式存储,否则会导致在使用完定时器,清除定时器,无法清除干净,定时器仍然还在,(特别是页面定时器)

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

const ChallengeModal = (props) => {
  const [timesContent, setTimesContent] = useState("");
  const [timer, setTimer] = useState(null);
 
  const handleCancelStatus = (e) => {
    clearInterval(timer);
  };
 
  const setTime = (val) => {
    let times = val;
    let h = 0,
      m = 0,
      s = 0;
    if (times > 0) {
      h = Math.floor(times / 60);
      m = Math.floor(times) - h * 60;
      s = Math.floor(times * 60) - m * 60;
    }
    if (h <= 9) h = "0" + h;
    if (m <= 9) m = "0" + m;
    if (s <= 9) s = "0" + s;
    if (s === 0) s = "00";
    setTimesContent(h + ":" + m + ":" + s);
  };

  // 造计时器
  const makeTime = () => {
    let  limit_time  =60;
    let times = limit_time * 60;
    // let timer = null;
    const MeTimer = setInterval(() => {
      let h = 0,
        m = 0,
        s = 0;
      if (times > 0) {
        h = Math.floor(times / (60 * 60));
        m = Math.floor(times / 60) - h * 60;
        s = Math.floor(times) - h * 60 * 60 - m * 60;
      }
      if (h <= 9) h = "0" + h;
      if (m <= 9) m = "0" + m;
      if (s <= 9) s = "0" + s;
      setTimesContent(h + ":" + m + ":" + s);
      times--;
      if (times < 0) {
        console.log("122");
        clearInterval(timer);
      }
    }, 1000);
    setTimer(MeTimer);
    console.log("times", times);
   };
   const closeTime =()=>{
  	 clearInterval(timer);
      setTimer(null);
   }
   useEffect(() => {
    setTime(timer)
   }, []);
  return (
    <div>
     <button onClick={()=>makeTime()}>打开</button>
     {timesContent}
     <button onClick={()=>closeTime()}>关闭</button>
    </div>
  );
};
export default ChallengeModal;

你可能感兴趣的:(hooks,react.js,javascript,前端)