Redux中高阶组件connect原理

218 阅读1分钟

connect基本用法:

export class About extends PureComponent {
    render() {
    }
}

const mapStateToProps = (state) => ({
    counter: state.counter
})

const mapDispatchToProps = (dispatch) => {
    changeCounter(num) {
        // 在这里派发action
        dispatch(cahngeCounter)
    }
}

// 调用connect函数返回高阶组件,再调用该高阶组件,该组件自动继承得到redux里的state和action数据
export default connect(mapStateToProps, mapDispatchToProps)(About)

实现简易版connnect高阶函数:

入参:
1.函数:mapStateToProps
2.函数:mapDispatchToProps
返回值:
函数,即高阶组件

export function connect(mapStateToProps, mapDispatchToProps) {
    // 高阶组件:传入一个组件,返回一个组件
    return function(WrapperComponent) {
        class NewComponent extends PureComponent {
            constructor() {
                super()
                this.state = mapStateToProps(store.getState())
            }

            componentDidMount() {
                // 对数据进行监听,才能响应redux发生的更新操作
                this.unsubscribe = store.subscribe(() => {
                    // pureComponent底层做了浅层拷贝,知道哪些数据发生了改变,从而发生对应的更新
                    this.setState(mapStateToProps(store.getState()))
                })
            }

            componentWillUnmount() {
                this.unsubscribe()
            }
            
            render() {
                // 调用mapStateToProps函数,传入state,返回一个对象
                const stateObj = mapStateToProps(store.getState())
                // 调用mapDIspatchToProps,传入dispatch
                const dispatchObj = mapDispatchToProps(store.dispatch)
                return <WrapperComponent {...this.props} {...this.stateObj} {...dispatchObj} />
            }
        }
        return NewComponent
    }
}