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