react 創(chuàng)建單例組件的方法
需求背景
最近有個(gè)需求,需要在項(xiàng)目中添加一個(gè)消息通知彈窗,告知用戶一些信息。
用戶看過消息后,就不再彈窗了。
問題
很明顯,這個(gè)需要后端的介入,提供相應(yīng)的接口(這樣可擴(kuò)展性更好)。
在開發(fā)過程中,遇到個(gè)問題:由于我們的系統(tǒng)是多頁面的,所以每次切換頁面,都會去請求后端的消息接口。。有一定的性能損耗。
因?yàn)槭嵌囗撁嫦到y(tǒng),使用單例組件貌似也沒啥意義(不過是個(gè)機(jī)會學(xué)習(xí)學(xué)習(xí)單例組件是怎么寫的)。
于是,想到使用瀏覽器緩存來記錄是否彈過窗了(當(dāng)然,得設(shè)定過期時(shí)間)。
如何寫單例組件
1、工具函數(shù):
import ReactDOM from 'react-dom';
/**
* ReactDOM 不推薦直接向 document.body mount 元素
* 當(dāng) node 不存在時(shí),創(chuàng)建一個(gè) 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} />;
}
}
// 使用上面的工具函數(shù)
export const loading = domRender(<SingletonLoading />);
3、使用組件:
import loading from 'xxx'; // ... loading.start(); loading.stop();
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Remix后臺開發(fā)之remix-antd-admin配置過程
這篇文章主要為大家介紹了Remix后臺開發(fā)之remix-antd-admin配置過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
詳解在React項(xiàng)目中如何集成和使用web worker
在復(fù)雜的React應(yīng)用中,某些計(jì)算密集型或耗時(shí)操作可能會阻塞主線程,導(dǎo)致用戶界面出現(xiàn)卡頓或響應(yīng)慢的現(xiàn)象,為了優(yōu)化用戶體驗(yàn),可以采用Web Worker來在后臺線程中執(zhí)行這些操作,本文將詳細(xì)介紹在React項(xiàng)目中如何集成和使用Web Worker來改善應(yīng)用性能,需要的朋友可以參考下2023-12-12
react中實(shí)現(xiàn)搜索結(jié)果中關(guān)鍵詞高亮顯示
這篇文章主要介紹了react中實(shí)現(xiàn)搜索結(jié)果中關(guān)鍵詞高亮顯示,使用react實(shí)現(xiàn)要比js簡單很多,方法都是大同小異,具體實(shí)現(xiàn)代碼大家跟隨腳本之家小編一起看看吧2018-07-07
詳解在React.js中使用PureComponent的重要性和使用方式
這篇文章主要介紹了詳解在React.js中使用PureComponent的重要性和使用方式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07
使用React?MUI庫實(shí)現(xiàn)用戶列表分頁功能
MUI是一款基于React的UI組件庫,可以方便地構(gòu)建美觀的用戶界面,使用MUI的DataTable組件和分頁器組件可以輕松實(shí)現(xiàn)用戶列表分頁功能,這篇文章使用MUI庫實(shí)現(xiàn)了用戶列表分頁功能,感興趣的同學(xué)可以參考下文2023-05-05
一文詳解ReactNative狀態(tài)管理redux-toolkit使用
這篇文章主要為大家介紹了ReactNative狀態(tài)管理redux-toolkit使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

