【问题标题】:What does the @ in front of a function call mean? [duplicate]函数调用前面的@是什么意思? [复制]
【发布时间】:2015-10-07 23:14:15
【问题描述】:

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} />;
      }
    };
  };
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6 babeljs


    【解决方案1】:

    那些@ES7 decorators(它们通过Babel 转译)。来自规范:

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

    // A simple decorator
    @annotation
    class MyClass { }
    
    function annotation(target) {
       // Add a property on target
       target.annotated = true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 2015-05-23
      相关资源
      最近更新 更多