最近有个需求,须要在项目中添加一个消息通知弹窗,告知用户一些信息。
用户看过消息后,就再也不弹窗了。javascript
很明显,这个须要后端的介入,提供相应的接口(这样可扩展性更好)。java
在开发过程当中,遇到个问题:因为咱们的系统是多页面的,因此每次切换页面,都会去请求后端的消息接口。。有必定的性能损耗。node
由于是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
因而,想到使用浏览器缓存来记录是否弹过窗了(固然,得设定过时时间)。react
一、工具函数:后端
import ReactDOM from 'react-dom'; /** * ReactDOM 不推荐直接向 document.body mount 元素 * 当 node 不存在时,建立一个 div */ function domRender(reactElem, node) { let div; if (node) { div = typeof node === 'string' ? window.document.getElementById(node) : node; } else { div = window.document.createElement('div'); window.document.body.appendChild(div); } return ReactDOM.render(reactElem, div); }
二、组件:浏览器
export class SingletonLoading extends Component { 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}); } get isGlobalLoading() { return this.state.isGlobal && this.state.show; } get noWaiting() { return this.noGlobalWaiting && this.pageLoadingCount < 1; } get toPageLoading() { return this.noGlobalWaiting && this.isGlobalLoading; } get noGlobalWaiting() { return this.globalLoadingCount < 1; } render() { return <BreakLoading {...this.state} />; } } // 使用上面的工具函数 export const loading = domRender(<SingletonLoading />);
三、使用组件:缓存
import loading from 'xxx'; // ... loading.start(); loading.stop();