反应创建单例组件的方法

  

<强>需求背景
  

  

最近有个需求,需要在项目中添加一个消息通知弹窗,告知用户一些信息。
  

  

用户看过消息后,就不再弹窗了。

  

<强>问题
  

  

很明显,这个需要后端的介入,提供相应的接口(这样可扩展性更好)。

  

在开发过程中,遇到个问题:由于我们的系统是多页面的,所以每次切换页面,都会去请求后端的消息接口. .有一定的性能损耗。

  

因为是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
  于是,想到使用浏览器缓存来记录是否弹过窗了(当然,得设定过期时间)。

  

<>强如何写单例组件
  

  

1,工具函数:

        从“进口ReactDOM react-dom ';/* *   * ReactDOM不推荐直接向文档。身体山元素   *当节点不存在时,创建一个div   */函数domRender (reactElem、节点){   让div;   如果(节点){   div=typeof节点==='字符串'   & # 63;window.document.getElementById(节点)   :节点;   其他}{   div=window.document.createElement (div);   window.document.body.appendChild (div);   }   ReactDOM返回。呈现(reactElem div);   }   之前      

2组件:

        出口类SingletonLoading扩展组件{   globalLoadingCount=0;   pageLoadingCount=0;      状态={   显示:假的,   名称:”,   isGlobal:未定义的   }      滞后时间=零;      开始=(选项={})=比;{//?   }      停止=(选项={})=比;{//?   }      stopAll () {   如果(! this.state.show)返回;   这一点。globalLoadingCount=0;   这一点。pageLoadingCount=0;   这一点。设置状态({显示:假});   }      得到isGlobalLoading () {   this.state返回。isGlobal,,this.state.show;   }      得到noWaiting () {   返回。noGlobalWaiting,,这一点。pageLoadingCount & lt;1;   }      得到toPageLoading () {   返回。noGlobalWaiting,,this.isGlobalLoading;   }      得到noGlobalWaiting () {   返回。globalLoadingCount & lt;1;   }      呈现(){   返回& lt; BreakLoading{…这个。国家}/祝辞;;   }   }//使用上面的工具函数   出口const加载=domRender (& lt; SingletonLoading/祝辞);      之前      

3,使用组件:

        从“xxx”进口加载;//?   loading.start ();   loading.stop ();      之前      

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

反应创建单例组件的方法