1

Link to project referred to The project linked to has a function called connectToStores that gets imported like this (with es6 syntax)

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

However, when it gets called (see link above), there is a @ put in front

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

The original connectToStores function is a seemingly regular exported function. Why is there @ put in front of it?

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} />;
      }
    };
  };
}
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
Leahcim
  • 40,649
  • 59
  • 195
  • 334

1 Answers1

3

Those @ are ES7 decorators (they are transpiled through Babel). From the specification:

It is also possible to decorate a class. In this case, the decorator takes the target constructor.

// A simple decorator
@annotation
class MyClass { }

function annotation(target) {
   // Add a property on target
   target.annotated = true;
}
Buzinas
  • 11,597
  • 2
  • 36
  • 58