react hooks中如何关闭setInterval的定时器

最近在使用函数式组件中发现在离开页面时无法关闭定时器,找了好多方法后终于搞定,
如下:重点useRef

import { useState, useEffect, useRef } from 'react'

const Pay = ({ router }) => {
  let timer=useRef();
  
  useEffect(()=>{
    startTimer(); // 开启定时器
    return()=>{
      console.log('离开页面------------');
      stopTimer()
    }
  }, [])
  
  // 开启定时器
  const startTimer = () => {
    timer.current = setInterval(()=>{
      console.log('循环定时器');
    }, 1000)
  }

  // 关闭
  const stop = () =>{
    clearInterval(timer.current);
  }
  
  // ...
  <button onClick={()=>stop()}>停止定时器</button>
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u012570307/article/details/126424323
今日推荐