手动实现redux(四)

本节我们来解决下手动实现redux(三)中代码重复冗余问题。

上一节中,我们在创建组件时,有大量公共代码。

  1. 需要手动引入store, 需要在组件中建立store到组件本身的state的映射关系;
  2. 需要在组件的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();
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/paopaolee/p/9509317.html
今日推荐