首頁  >  文章  >  web前端  >  如何使用react建立單例元件

如何使用react建立單例元件

php中世界最好的语言
php中世界最好的语言原創
2018-06-02 10:18:361444瀏覽

這次帶給大家如何使用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();

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

如何使用vue中filter

#怎麼用vue判斷dom的class

以上是如何使用react建立單例元件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn