週末嘗試了一下React新的hooks功能,來封裝一個組件,遇到一個bug,因此記錄一下過程!html
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 Notificationreact
大概意思是組件已經卸載了,但在卸載以後還執行了一個對組件更新的操做,這是一個無效的操做,但它表示應用程序中存在內存泄漏。要修復,請取消useEffect cleanup function.in Notification 中的全部訂閱和異步任務webpack
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`}> ……//首席填坑官∙蘇南的專欄 交流:91259409五、公衆號:honeyBadger8 </div> <p className={`${prefixCls}-notice-colse`} title="關閉" onClick={()=>leave("手動點擊的關閉")}><Svg/></p> </div> ); };
useEffect
方法,是react新增的,它是componentDidMount
,componentDidUpdate
、componentWillUnmount
三個生命週期的合集,進場
、出場
兩函數,出場
即leave方法,這個邏輯是正常的,leave
,也就是onclick事件上,useEffect
方法裏return 一個方法,它是能夠在組件卸載時執行的,const intervalRef = useRef()
;指定賦值後能同步更新,以前的timer手動執行沒有拿到timer因此沒有清除掉;中文,英文的沒有找到 文檔英文的也補一下吧 react github也有人提到這個問題,學習了git
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);//首席填坑官∙蘇南的專欄 交流:91259409五、公衆號: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`}> ……//首席填坑官∙蘇南的專欄 交流:91259409五、公衆號:honeyBadger8 </div> <p className={`${prefixCls}-notice-colse`} title="關閉" onClick={()=>leave("手動點擊的關閉")}><Svg/></p> </div> ); };
做者:蘇南 - 首席填坑官 連接:http://www.javashuo.com/article/p-aawoclhu-gh.html 交流:91259409五、公號:
honeyBadger8
本文原創,著做權歸做者全部。商業轉載請聯繫@IT·平頭哥聯盟
得到受權,非商業轉載請註明原連接及出處。github