这次给大家带来如何使用react创建单例组件,使用react创建单例组件的注意事项有哪些,下面就是实战案例,一起来看一下。
需求背景
最近有个需求,需要在项目中添加一个消息通知弹窗,告知用户一些信息。
用户看过消息后,就不再弹窗了。
问题
很明显,这个需要后端的介入,提供相应的接口(这样可扩展性更好)。
在开发过程中,遇到个问题:由于我们的系统是多页面的,所以每次切换页面,都会去请求后端的消息接口。。有一定的性能损耗。
因为是多页面系统,使用单例组件貌似也没啥意义(不过是个机会学习学习单例组件是怎么写的)。
于是,想到使用浏览器缓存来记录是否弹过窗了(当然,得设定过期时间)。
如何写单例组件
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();
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
如何使用vue中filter
怎样使用vue判断dom的class
以上就是如何使用react创建单例组件的详细内容。