周末尝试了一下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