函数调用前面的@是什么意思?

时间:2015-10-07 23:14:16

标签: javascript reactjs ecmascript-6 babeljs

Link to project referred to链接到的项目有一个名为connectToStores的函数,可以像这样导入(使用es6语法)

import connectToStores from '../utils/connectToStores'; 

然而,当它被调用时(参见上面的链接),前面有一个@

@connectToStores([RepoStore, StargazersByRepoStore, UserStore], getState)

原始的connectToStores函数是一个看似常规的导出函数。为什么@放在它前面?

export default function connectToStores(stores, getState) {
  return function (DecoratedComponent) {
    const displayName =
      DecoratedComponent.displayName ||
      DecoratedComponent.name ||
      'Component';

    return class StoreConnector extends Component {
      static displayName = `connectToStores(${displayName})`;

      constructor(props) {
        super(props);
        this.handleStoresChanged = this.handleStoresChanged.bind(this);

        this.state = getState(props);
      }

      componentWillMount() {
        stores.forEach(store =>
          store.addChangeListener(this.handleStoresChanged)
        );
      }

      componentWillReceiveProps(nextProps) {
        if (!shallowEqual(nextProps, this.props)) {
          this.setState(getState(nextProps));
        }
      }

      componentWillUnmount() {
        stores.forEach(store =>
          store.removeChangeListener(this.handleStoresChanged)
        );
      }

      handleStoresChanged() {
        this.setState(getState(this.props));
      }

      render() {
        return <DecoratedComponent {...this.props} {...this.state} />;
      }
    };
  };
}

1 个答案:

答案 0 :(得分:3)

那些UIApplicationOpenSettingsURLStringES7 decorators(它们是通过Babel转换而来的)。从规范:

  

也可以装饰一个类。在这种情况下,装饰器采用目标构造函数。

@