国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

react 創建單例組件的方法

2024-05-06 16:43:56
字體:
來源:轉載
供稿:網友

需求背景

最近有個需求,需要在項目中添加一個消息通知彈窗,告知用戶一些信息。

用戶看過消息后,就不再彈窗了。

問題

很明顯,這個需要后端的介入,提供相應的接口(這樣可擴展性更好)。

在開發過程中,遇到個問題:由于我們的系統是多頁面的,所以每次切換頁面,都會去請求后端的消息接口。。有一定的性能損耗。

因為是多頁面系統,使用單例組件貌似也沒啥意義(不過是個機會學習學習單例組件是怎么寫的)。
于是,想到使用瀏覽器緩存來記錄是否彈過窗了(當然,得設定過期時間)。

如何寫單例組件

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();

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临泽县| 读书| 洞口县| 杭锦后旗| 普定县| 沙坪坝区| 江安县| 青冈县| 会泽县| 土默特右旗| 丰镇市| 峡江县| 平湖市| 台前县| 永州市| 格尔木市| 曲水县| 亳州市| 司法| 罗田县| 五河县| 东乌| 金堂县| 建昌县| 潼关县| 宁化县| 湖北省| 嘉义市| 油尖旺区| 黑龙江省| 遂溪县| 陕西省| 刚察县| 镇巴县| 四川省| 扬州市| 康乐县| 汶上县| 宜兰市| 贵阳市| 乌鲁木齐市|