本节我们来解决下手动实现redux(三)中代码重复冗余问题。
上一节中,我们在创建组件时,有大量公共代码。
- 需要手动引入store, 需要在组件中建立store到组件本身的state的映射关系;
- 需要在组件的componentWillMount中订阅事件, 在componentWillUnmount中取消订阅。
手动实现connect
import store from 'store'
const connect = (mapStateToProps, mapDispatchToProps)=>(WrappedComponent)=>{
this.state = store.getState()
class Proxy extends Component{
componentWillMount(){
this.unsubscribe = store.subscribe(()=>{
this.state = store.getState
});
}
componentWillUnmount(){
this.unsubscribe();
}
}
}