首页 / REACT / react实现单例组件(附代码)
react实现单例组件(附代码)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了react实现单例组件(附代码),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2005字,纯文字阅读大概需要3分钟。
内容图文
![react实现单例组件(附代码)](/upload/InfoBanner/zyjiaocheng/288/b7756e186ed7494faa2be522c8c2b4ef.jpg)
需求背景
最近有个需求,需要在项目中添加一个消息通知弹窗,告知用户一些信息。
用户看过消息后,就不再弹窗了。
问题
很明显,这个需要后端的介入,提供相应的接口(这样可扩展性更好)。
在开发过程中,遇到个问题:由于我们的系统是多页面的,所以每次切换页面,都会去请求后端的消息接口。。有一定的性能损耗。
因为是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
于是,想到使用浏览器缓存来记录是否弹过窗了(当然,得设定过期时间)。
如何写单例组件
1、工具函数:
import ReactDOM from 'react-dom'; /** * ReactDOM 不推荐直接向 document.body mount 元素 * 当 node 不存在时,创建一个 p */ function domRender(reactElem, node) { let p; if (node) { p = typeof node === 'string' ? window.document.getElementById(node) : node; } else { p = window.document.createElement('p'); window.document.body.appendChild(p); } return ReactDOM.render(reactElem, p); }
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();
相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!
推荐阅读:
开发react项目步骤详解
怎样获取前端界面中的DOM元素绝对位置
以上就是react 实现单例组件(附代码)的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的react实现单例组件(附代码)全部内容,希望文章能够帮你解决react实现单例组件(附代码)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。