时间:2021-05-26
需求背景
最近有个需求,需要在项目中添加一个消息通知弹窗,告知用户一些信息。
用户看过消息后,就不再弹窗了。
问题
很明显,这个需要后端的介入,提供相应的接口(这样可扩展性更好)。
在开发过程中,遇到个问题:由于我们的系统是多页面的,所以每次切换页面,都会去请求后端的消息接口。。有一定的性能损耗。
因为是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
于是,想到使用浏览器缓存来记录是否弹过窗了(当然,得设定过期时间)。
如何写单例组件
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();以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
一、创建组件ES6class创建的组件语法更加简明,也更符合javascript。内部的方法不需要使用function关键字。React.createClass
在上一节中,我们讲到了React组件,说了如何使用ES6类创建一个React组件并在其他的地方使用它。这一节我们将讲到React组件的两大灵魂——props和s
vue创建高阶组件的实现不够react优雅,但那是vue和react的设计思想导致的。在react中一切都是函数,而在vue中,组件最终都是函数,但在开发时可以
1.Springbean组件”默认为单例模式scope=“singleton,运行JavaApplication容器启动时自动创建对象scope=“protot
上篇文章写到了redux实现组件数据共享的方法,但是在react中,redux作者提供了一个更优雅简便的模块实现react组件之间数据共享。那就是利用react