• 技术文章 >web前端 >js教程

    react创建单例组件步骤详解

    php中世界最好的语言php中世界最好的语言2018-05-15 11:48:36原创960
    这次给大家带来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项目编译后部署在非网站根目录方法详解

    jQuery中length与size()使用区别有哪些

    JS设计模式中链式调用使用解析

    以上就是react创建单例组件步骤详解的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:react 详解 步骤
    上一篇:JS实现微信红包随机算法(附代码) 下一篇:node做出微信个人号机器人步骤详解
    20期PHP线上班

    相关文章推荐

    精选22门好课,价值3725元,开通VIP免费学习!• 一文了解Node中的文件模块和核心模块• JavaScript怎么处理树状结构数据的增删改查• 浅显易懂的JavaScript引入• 聊聊Angular Route中怎么提前获取数据• node.js gm是什么
    1/1

    PHP中文网