New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

decorator-loading

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

decorator-loading

解决页面loading逻辑的复用于业务的解耦

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

decorator-loading

❗️❗️背景

在项目中使用 loading,一般是在组件中用一个变量( 如 isLoading)来保存请求数据时的 loading 状态,请求 api 前将 isLoading 值设置为 true,请求 api 后再将 isLoading 值设置为 false,从而对实现 loading 状态的控制,但是如果很多异步需求都这样做势必会增加冗余代码,而且对 loading 状态的控制与我们的业务完全无关,我们完全可以解耦出来,所以使用装饰器抽离这部分逻辑代码

⛽️⛽️如何使用

import loading from "decorator-loading"
class Demo extends React.Component<any, any> {
  constructor(props: any) {
    super(props)
    this.state = {
      count: 0
    }
  }
 @loading()
  public  sendGetDemoReq() {
    axios.get('/user?ID=12345')
            .then(function (response) {
              // handle success
              console.log(response);
      })
  }
  public render() {
    return (
      <div styleName="page-demo">
        <h2>hellos 🍺🍺🍺🍺🍺🍺</h2>
        <Button onClick={this.sendGetDemoReq} type="primary" style={{ marginTop: '8px' }}>
          request
        </Button>
        {window.isLoading&&<YourLoading />}
      </div>
    )
  }
}

参数

现在支持的是一个全局window参数,所以我们建议你初始化的时候就先把这个参数挂载到window上,当然你如果不想挂载到window上,而是自定义变量(现在还没有支持这个操作),你可以直接copy这个装饰器代码进行修改

参数名
window.isLoadingfalse

装饰器代码

module.exports = loading = () => {
  return function (
    target,
    name,
    descriptor
  ) {
    let v
    return {
      enumerable: true,
      configurable: true,
      get: function () {
        if (descriptor) {
          v = descriptor.value
        }
        if (typeof v === 'function') {
          return async function () {
            window.isLoading = true
            try {
              await v.apply(this, arguments)
            } catch (error) {
              // 做一些错误上报之类的处理 
              throw error;
            } finally {
              window.isLoading = false
            }

          }
        }
      },
      set: function (c) {
        v = c;
      }
    }
  }
}

注意⚠️

如果是你的项目有配置ts需要在tsconfig配置 "experimentalDecorators": true

Keywords

decorator-loading

FAQs

Package last updated on 24 Oct 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts