React16.7 hooks之setTimeout引發(fā)的bug

React16.7 hooks之setTimeout引發(fā)的bug

前言

周末嘗試了一下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

大概意思是組件已經(jīng)卸載了,但在卸載之后還執(zhí)行了一個對組件更新的操作,這是一個無效的操作,但它表示應(yīng)用程序中存在內(nèi)存泄漏。要修復(fù),請取消useEffect cleanup function.in Notification 中的所有訂閱和異步任務(wù)

Can't perform a React state update on an unmounted component.,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();
  }
  
  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="關(guān)閉" onClick={()=>leave("手動點擊的關(guān)閉")}><Svg/></p>
    </div>
  );
};

簡單分析:

  • 首先useEffect方法,是react新增的,它是componentDidMountcomponentDidUpdate、componentWillUnmount三個生命周期的合集,
  • 也就是之前的寫法,上面三生命周期里會執(zhí)行到的操作,useEffect都會去做;
enter、leave方法
  • 很好理解,進場、出場兩函數(shù),
  • 進場:加了個定時器,在N秒后執(zhí)行出場即leave方法,這個邏輯是正常的,
  • 問題就出在手動執(zhí)行leave,也就是onclick事件上,
問題原因:
  • 其實就是在點擊事件的時候,沒有獲取到 timer的id,導(dǎo)致了定時器沒有清除掉;
    ??!看圖說話:
React v16.7 "Hooks" - What to Expect
解決思路:
  • 當然是看官方文檔,hooks對我來說也是個新玩意,不會~
  • 1、useEffect方法里return 一個方法,它是可以在組件卸載時執(zhí)行的,
  • 2、清除定時器它有自己的方式,const intervalRef = useRef();指定賦值后能同步更新,之前的timer手動執(zhí)行沒有拿到timer所以沒有清除掉;
React v16.7 "Hooks" - What to Expect
參考鏈接:

中文,英文的沒有找到
文檔英文的也補一下吧
react github也有人提到這個問題,學(xué)習(xí)了

完美解決:

請取消useEffect cleanup function.in Notification 中的所有訂閱和異步任務(wù)

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);//首席填坑官?蘇南的專欄 交流:912594095、公眾號:honeyBadger8
      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`}>
        ……//首席填坑官?蘇南的專欄 交流:912594095、公眾號:honeyBadger8
      </div>
      <p className={`${prefixCls}-notice-colse`} title="關(guān)閉" onClick={()=>leave("手動點擊的關(guān)閉")}><Svg/></p>
    </div>
  );
};

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

熱門推薦

作者:蘇南 - 首席填坑官
鏈接:https://blog.csdn.net/weixin_43254766/article/details/83758660
交流:912594095、公眾號:honeyBadger8
本文原創(chuàng),著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系@IT·平頭哥聯(lián)盟獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明原鏈接及出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 13,913評論 2 59
  • It's a common pattern in React to wrap a component in an ...
    jplyue閱讀 3,379評論 0 2
  • 這幅畫是臨摹的@心藍丫頭 的日落撒哈拉。本以為會花一點時間,結(jié)果邊看電影邊畫不知不覺就畫完了。 之前一直都有關(guān)注彩...
    阿遙遙閱讀 369評論 2 4
  • 1、onExit onExit的使用 用attribute((cleanup(...)))修飾了rac_clean...
    林煒超閱讀 687評論 0 0
  • 夏天的農(nóng)村,有暴雨有池塘,有蛙叫有蟬鳴,有河壩邊的田螺有麥田里的麥穗,有紅薯地里的大豆蟲有墳?zāi)苟牙锏拇笪涷啤?秋...
    之葤閱讀 417評論 1 3

友情鏈接更多精彩內(nèi)容