Home >Web Front-end >JS Tutorial >How to create a singleton component using react
This time I will show you how to use react to create a singleton component. What are the notes of using react to create a singleton component. The following is a practical case, let's take a look.
Requirement Background
Recently there was a requirement to add a message notification pop-up window to the project to inform the user of some information.
After the user reads the message, the pop-up window will no longer appear.
Problem
Obviously, this requires the intervention of the backend to provide the corresponding interface (so that the scalability is better).
During the development process, we encountered a problem: Since our system is multi-page, every time we switch pages, we will request the back-end message interface. . There is a certain performance loss.
Because it is a multi-page system, there seems to be no point in using singleton components (but it is an opportunity to learn how to write singleton components).
So, I thought of using the browser cache to record whether the pop-up window has popped up (of course, the expiration time must be set).
How to write a singleton component
1. Tool function:
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. Component:
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. Using components :
import loading from 'xxx'; // ... loading.start(); loading.stop();
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
##How to use vue to determine the class of dom
The above is the detailed content of How to create a singleton component using react. For more information, please follow other related articles on the PHP Chinese website!