React Mixins Are Dead in ES6
背景
从React官网 文档 v0.13 上我们可以看到, 关于Mixins很多时候,不同的组件可能需要使用到一些公共的方法,Minxins 可以包装这些公共的方法暴露给外部调用。很多情况下,我们会定义一些React生命周期的方法,React 会自动地帮我们把这些方法合并到component 内,这些方法也将被组件所调用。 但是,使用Mixins也会导致一些问题,主要有以下几个原因。
Higher-Order ComponentsHigher-Order Components是其中一种替代 Mixins 的其中一种解决方案,现在我们先来看一个 用 javascriptfunction StoreMixin(...stores) {
var Mixin = {
getInitialState() {
return this.getStateFromStores(this.props);
},componentDidMount() {
stores.forEach(store =>
store.addChangeListener(this.handleStoresChanged)
);
this.setState(this.getStateFromStores(this.props));
},componentWillUnmount() {
stores.forEach(store =>
store.removeChangeListener(this.handleStoresChanged)
);
},handleStoresChanged() {
if (this.isMounted()) {
this.setState(this.getStateFromStores(this.props));
}
}
};
return Mixin;
}
在使用的时候,我们先把 javascriptvar UserProfilePage = React.createClass({
mixins: [StoreMixin(UserStore)],propTypes: {
userId: PropTypes.number.isRequired
},getStateFromStores(props) {
return {
user: UserStore.get(props.userId);
}
}
render() {
var { user } = this.state;
return <div>{user ? user.name : 'Loading'}</div>;
}
这样,当UserProfilePage 在渲染的时候就会触发 StoreMixin 中定义的一些生命周期的方法,监听Store数据变化。变化之后触发响应的处理函数。 什么是 higher-order component ?
嗯,听起来有点拗口,我们来举个例子看看就明白了。 javascriptfunction connectToStores(Component,stores,getStateFromStores) {
const StoreConnection = React.createClass({
getInitialState() {
return getStateFromStores(this.props);
},componentDidMount() {
stores.forEach(store =>
store.addChangeListener(this.handleStoresChanged)
);
},handleStoresChanged() {
if (this.isMounted()) {
this.setState(getStateFromStores(this.props));
}
},render() {
return <Component {...this.props} {...this.state} />;
}
});
return StoreConnection;
};
推荐ract-dnd 一个专注于控件拖拽的库,是基于 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
