装饰器的练习(一)

163 阅读2分钟

“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 3 天,点击查看活动详情

前言

在学习本篇之前需要有一定基础知识,在此基础上可以更好的完成各种类型的挑战,编写出属于自己的类型工具;

1.简介

装饰器decorator 是一种对类进行处理的函数,是 Es6 的一个语法糖,是一种与类(class)相关的语法,用来注释或修改类和方法以@+函数名形式展现,可以放在类和类方法的定义前面

在react中使用装饰器方式时,需要做一些配置修改,create-react-app默认不支持装饰器模式。

如果你的项目已经使用了typeScript,那只需要在tsconfig.json文件中的experimentalDecorators 设置为true 就可以了

{
    "compilerOptions": {
        "experimentalDecorators": true,
    }
}

2.实战

1.使用装饰器实现一个计算时间的装饰器

1.方法装饰器函数有三个参数:

  • target ———— 当前对象的原型
  • propertyKey ———— 方法的名称
  • descriptor ———— 方法的属性描述符
export function computingTime() {
    return function(target:Object, property:string, descriptor:PropertyDescriptor) {
       //缓存原始值
        const oldValue = descriptor.value; 

        descriptor.value = async function() {
            let startTime = Date.now();
            //调用原始的方法,调用原始逻辑
            let value = await oldValue.apply(this, arguments); 

            //实现计算时间的逻辑
            let time = Date.now() - startTime;
            console.log("消耗了:" + time);

            return value;
        };
        return descriptor;
    };
}

调用装饰器

  @computingTime()
  async componentDidMount() {
    await this.longTime();
  }

  longTime() {
    return new Promise((resolve) => {
      setTimeout(resolve, 2000);
    });
  }

2.使用装饰器实现一个发送请求出现loading

export function loadingWrap(needHide) {

  const defaultLoading = (
    <div className="toast-loading">
      <Loading className="loading-icon"/>
      <div>加载中...</div>
    </div>
  );

  return function (target, property, descriptor) {
    const raw = descriptor.value;
    
    descriptor.value = function (...args) {
      Toast.info(text || defaultLoading, 0, null, true);
      const res = raw.apply(this, args);
      
      if (needHide) {
        if (get('finally')(res)) {
          res.finally(() => {
            Toast.hide();
          });
        } else {
          Toast.hide();
        }
      }
    };
    return descriptor;
  };
}

结束语

希望大家能够喜欢我的文章,我真的很用心在写,也希望通过文章认识更多志同道合的朋友。

最后伙伴们,如果喜欢我的可以给点一个小小的赞👍或者关注➕都是对我最大的支持。