视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
react 创建单例组件的方法
2020-11-27 22:15:35 责编:小采
文档


需求背景

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

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

问题

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

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

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

如何写单例组件

1、工具函数:

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);
}

2、组件:

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 />);

3、使用组件:

import loading from 'xxx';

// ...
loading.start();
loading.stop();

下载本文
显示全文
专题