高级技术员研习react 创建单例组件的方法
时间:2022-01-18 01:14:35|来源:网络精心整理
这篇文章主要讲解的是react 创建单例组件的方法,文章内容非常详细,相信一定可以解决你的问题,需要的朋友可以参考下哦
需求背景
最近有个需求,需要在项目中添加一个消息通知弹窗,告知用户一些信息。
用户看过消息后,就不再弹窗了。
问题
很明显,这个需要后端的介入,提供相应的接口(这样可扩展性更好)。
在开发过程中,遇到个问题:由于我们的系统是多页面的,所以每次切换页面,都会去请求后端的消息接口。。有一定的性能损耗。
因为是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
于是,想到使用浏览器缓存来记录是否弹过窗了(当然,得设定过期时间)。
如何写单例组件
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();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持它帮你网。
上一篇:站长讲解JavaScript实现微信红包算法及问题解决方法
本文地址:https://www.tabangni.com/jsstudy/29183.html
查看更多与“react单例”有关的文章
推荐阅读
- 1高级技术员研习react 创建单例组件的方法
- 2专业技术员解惑Javascript的表单验证长度
- 3大神讲说JavaScript判断是否是微信浏览器
- 4资深技术员解读基于BootStrap的Metronic框架实现页面链接收藏夹功能按钮移动收藏记录(使用Sortable进行拖动排序)
- 5图文介绍简单谈谈JS数组中的indexOf方法
- 6主编解惑深入理解Javascript中的作用域链和闭包
- 7顶级人才叙述12个非常有用的JavaScript技巧
- 8大师讲说JavaScript异步上传图片文件的实例代码
- 9专家说明javascript导出csv文件(excel)的方法示例
- 10权威技术员普及Phaser.js实现简单的跑酷游戏附源码下载
最近更新
- 01-18高级技术员研习react 创建单例组件的方法
- 01-18Oralce中VARCHAR2()与NVARCHAR2()的区别介绍
- 01-18Dreamweaver站点怎么检查链接错误?
- 01-18专业技术员解惑Javascript的表单验证长度
- 01-18php文件缓存类用法实例分析
- 01-18asp.net为网页动态添加关键词的方法
- 01-18浅析php-fpm静态和动态执行方式的比较
- 01-18大神讲说JavaScript判断是否是微信浏览器
- 01-18PHP设计模式之模板方法模式定义与用法详解
- 01-18ASP.NET 中的Application详解