react 创建单例组件的方法
需求背景
最近有个需求,需要在项目中添加一个消息通知弹窗,告知用户一些信息。
用户看过消息后,就不再弹窗了。
问题
很明显,这个需要后端的介入,提供相应的接口(这样可扩展性更好)。
在开发过程中,遇到个问题:由于我们的系统是多页面的,所以每次切换页面,都会去请求后端的消息接口。。有一定的性能损耗。
因为是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
于是,想到使用浏览器缓存来记录是否弹过窗了(当然,得设定过期时间)。
如何写单例组件
1、工具函数:
importReactDOMfrom'react-dom';
/**
*ReactDOM不推荐直接向document.bodymount元素
*当node不存在时,创建一个div
*/
functiondomRender(reactElem,node){
letdiv;
if(node){
div=typeofnode==='string'
?window.document.getElementById(node)
:node;
}else{
div=window.document.createElement('div');
window.document.body.appendChild(div);
}
returnReactDOM.render(reactElem,div);
}
2、组件:
exportclassSingletonLoadingextendsComponent{
globalLoadingCount=0;
pageLoadingCount=0;
state={
show:false,
className:'',
isGlobal:undefined
}
delayTimer=null;
start=(options={})=>{
//...
}
stop=(options={})=>{
//...
}
stopAll(){
if(!this.state.show)return;
this.globalLoadingCount=0;
this.pageLoadingCount=0;
this.setState({show:false});
}
getisGlobalLoading(){
returnthis.state.isGlobal&&this.state.show;
}
getnoWaiting(){
returnthis.noGlobalWaiting&&this.pageLoadingCount<1;
}
gettoPageLoading(){
returnthis.noGlobalWaiting&&this.isGlobalLoading;
}
getnoGlobalWaiting(){
returnthis.globalLoadingCount<1;
}
render(){
return ;
}
}
//使用上面的工具函数
exportconstloading=domRender( );
3、使用组件:
importloadingfrom'xxx'; //... loading.start(); loading.stop();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。