Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript中装饰器的应用 #31

Open
zp1112 opened this issue Aug 7, 2020 · 0 comments
Open

javascript中装饰器的应用 #31

zp1112 opened this issue Aug 7, 2020 · 0 comments

Comments

@zp1112
Copy link
Owner

zp1112 commented Aug 7, 2020

装饰器

打印console.log

调试的时候经常需要打印一些log来查看,这时候直接展开function,在return之前加console似乎比较繁琐,可以写一个装饰器log来装饰这个func,使之在return之前打印结果。

function log(target, name, descriptor) {
  var oldValue = descriptor.value;
  descriptor.value = function () {
    const res = oldValue.apply(null, arguments);
    console.log(`Calling "${name}" and return `, res);
    return res;
  };

  return descriptor;
}
class App extends React.Component {
  @log
  add() {
    return 3;
  }
  componentDidMount() {
    this.add()
  }
  render() {
    return 111;
  }
}

react中为每个路由页面添加title

类似于高阶组件的写法,装饰器需要传参数的时候再包裹一层函数

const setTitle = (title) => (WrappedComponent) => {
  return class extends React.Component {
    componentDidMount() {
      document.title = title
    }
    render() {
      return <WrappedComponent {...this.props} />
    }
  }
}
@setTitle('Profile Page')
class App extends React.Component {
  render() {
    return 111;
  }
}

使用connect装饰器

redux提供connect可以使用装饰器写法

@connect(() => {
  return {
    count: state.count
  }
},
(dispatch) => {
  increcement: () => dispatch(increcementAction())
})
class App extends React.Component{
  ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant