1. 程式人生 > >React16.7 hooks初探之定時器引發的問題

React16.7 hooks初探之定時器引發的問題

本文由@IT·平頭哥聯盟-首席填坑官∙蘇南 分享,公眾號:honeyBadger8,webpack4,從0配置到專案搭建

前言

週末嘗試了一下React新的hooks功能,來封裝一個元件,遇到一個bug,所以記錄一下過程!

報錯如下:

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.in

Notification

大概意思是元件已經解除安裝了,但在解除安裝之後還執行了一個對元件更新的操作,這是一個無效的操作,但它表示應用程式中存在記憶體洩漏。要修復,請取消useEffect cleanup function.in Notification 中的所有訂閱和非同步任務
![Can’t perform a React state update on an unmounted component.,Read the Motivation to learn why we’re introducing Hooks to React](https://img-blog.csdnimg.cn/20181205213235623.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzI1NDc2Ng==,size_16,color_FFFFFF,t_70

"React v16.7 “Hooks” - What to Expect,Read the Motivation to learn why we’re introducing Hooks to React. ")

元件核心程式碼如下:


function Notification(props){
  var timer = null;
  const [visible, setVisible] = useState(false);
  let {title,description,duration,theme,onClose,}= props;
  let leave = (source=
'') => { clearTimeout(timer); setVisible(false); console.log("注意這裡是 leave方法裡,timer的id:"+timer,"事件的來源:",source); console.log("leave result:",timer); onClose&&onClose();//首席填坑官∙蘇南的專欄 交流:912594095、公眾號:honeyBadger8 } let enter = () => { setVisible(true); if( duration > 0 ){ let timer = setTimeout(() => { console.log(`auto carried out`,timer) //timer Number Id leave(`Time to`); }, duration*1000); console.log(`enter方法裡,timer的id:`,timer) //timer Number Id } } useEffect(()=>{ enter(); },[]) return ( <div className={`${prefixCls}-notice`} style={{display:`${visible?'':'none'}`}}> {!!theme&&<p className={`${prefixCls}-notice-icon`}><Svg iconId={`svg-${theme}`} /></p>} <div className={`${prefixCls}-notice-content`}> ……//首席填坑官∙蘇南的專欄 交流:912594095、公眾號:honeyBadger8 </div> <p className={`${prefixCls}-notice-colse`} title="關閉" onClick={()=>leave("手動點選的關閉")}><Svg/></p> </div> ); };

簡單分析:

  • 首先useEffect方法,是react新增的,它是componentDidMountcomponentDidUpdatecomponentWillUnmount三個生命週期的合集,
  • 也就是之前的寫法,上面三生命週期裡會執行到的操作,useEffect都會去做;
enter、leave方法
  • 很好理解,進場出場兩函式,
  • 進場:加了個定時器,在N秒後執行出場即leave方法,這個邏輯是正常的,
  • 問題就出在手動執行leave,也就是onclick事件上,
問題原因:
  • 其實就是在點選事件的時候,沒有獲取到 timer的id,導致了定時器沒有清除掉;
    !!看圖說話:

React v16.7 "Hooks" - What to Expect -點選累加的計數器,公眾號:honeyBadger8

解決思路:
  • 當然是先看文件,hooks對我來說也是個新玩意,不會~
  • 1、useEffect方法裡return 一個方法,它是可以在元件解除安裝時執行的,
  • 2、清除定時器它有自己的方式,const intervalRef = useRef();指定賦值後能同步更新,之前的timer手動執行沒有拿到timer所以沒有清除掉;

點選累加的計數器,公眾號:honeyBadger8,首席填坑官∙蘇南的專欄 交流:912594095、公眾號:honeyBadger8

參考連結:

英文的沒有找到
英文的也補一下吧
github也有人提到這個問題,學習了

完美解決:

React v16.7 "Hooks" - What to Expect - 知乎,公眾號:honeyBadger8


function Notification(props){
  var timer = null;
  const [visible, setVisible] = useState(false);
  let {title,description,duration,theme,onClose,}= props;
  const intervalRef = useRef(null);
  let leave = (source='') => {
    clearTimeout(intervalRef.current);
    setVisible(false);
    console.log("leave result:",source,intervalRef);
    onClose&&onClose();
  }
  
  let enter = () => {
    setVisible(true);
    if( duration > 0 ){
      let id = setTimeout(() => {
        console.log(`auto carried out`,intervalRef) //timer Number Id 
        leave(`Time to`);
      }, duration*1000);
      intervalRef.current = id;
    }
  }

  useEffect(()=>{
    enter();
    return ()=>clearTimeout(intervalRef.current);
  },[])

  return (
    <div className={`${prefixCls}-notice`} style={{display:`${visible?'':'none'}`}}>
      {!!theme&&<p className={`${prefixCls}-notice-icon`}><Svg iconId={`svg-${theme}`} /></p>}
      <div className={`${prefixCls}-notice-content`}>
        ……
      </div>
      <p className={`${prefixCls}-notice-colse`} title="關閉" onClick={()=>leave("手動點選的關閉")}><Svg/></p>
    </div>
  );
};

歡迎關注公號,支援一下我們,謝謝!

寶劍鋒從磨礪出,梅花香自苦寒來,做有溫度的攻城獅!,公眾號:honeyBadger8

熱門推薦

作者:蘇南 - 首席填坑官

連結:https://www.susouth.com/other/2018/12/05/shared/

交流:912594095、公眾號:honeyBadger8

本文原創,著作權歸作者所有。商業轉載請聯絡@IT·平頭哥聯盟獲得授權,非商業轉載請註明原連結及出處。