react 創(chuàng)建單例組件的方法
需求背景
最近有個(gè)需求,需要在項(xiàng)目中添加一個(gè)消息通知彈窗,告知用戶一些信息。
用戶看過(guò)消息后,就不再?gòu)棿傲恕?/p>
問(wèn)題
很明顯,這個(gè)需要后端的介入,提供相應(yīng)的接口(這樣可擴(kuò)展性更好)。
在開發(fā)過(guò)程中,遇到個(gè)問(wèn)題:由于我們的系統(tǒng)是多頁(yè)面的,所以每次切換頁(yè)面,都會(huì)去請(qǐng)求后端的消息接口。。有一定的性能損耗。
因?yàn)槭嵌囗?yè)面系統(tǒng),使用單例組件貌似也沒啥意義(不過(guò)是個(gè)機(jī)會(huì)學(xué)習(xí)學(xué)習(xí)單例組件是怎么寫的)。
于是,想到使用瀏覽器緩存來(lái)記錄是否彈過(guò)窗了(當(dāng)然,得設(shè)定過(guò)期時(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();
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React 項(xiàng)目遷移 Webpack Babel7的實(shí)現(xiàn)
這篇文章主要介紹了React 項(xiàng)目遷移 Webpack Babel7的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09React函數(shù)組件與類組件使用及優(yōu)劣對(duì)比
本文主要介紹了React函數(shù)組件與類組件使用及優(yōu)劣對(duì)比,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04簡(jiǎn)單的React SSR服務(wù)器渲染實(shí)現(xiàn)
這篇文章主要介紹了簡(jiǎn)單的React SSR服務(wù)器渲染實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12react實(shí)現(xiàn)記錄拖動(dòng)排序
這篇文章主要介紹了react實(shí)現(xiàn)記錄拖動(dòng)排序的相關(guān)資料,需要的朋友可以參考下2023-07-07react中使用js實(shí)現(xiàn)頁(yè)面滾動(dòng)監(jiān)聽(推薦)
這篇文章主要介紹了react中使用js實(shí)現(xiàn)頁(yè)面滾動(dòng)監(jiān)聽,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-04-04React如何通過(guò)@craco/craco代理接口
這篇文章主要介紹了React如何通過(guò)@craco/craco代理接口問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10