用法
connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])
做用:链接React组件与Redux Store
mapStateToProps容许咱们将 store 中的数据做为 props 绑定到组件上
mapDispatchToProps将action做为props绑定到MyComp上。
mergeProps无论是stateProps仍是dispatchProps,都须要和ownProps merge 以后才会被赋给MyComp。connect的第三个参数就是用来作这件事。一般状况下,你能够不传这个参数,connect就会使用Object.assign替代该方法。
首先connect之因此会成功,是由于Provider组件:
在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
接收Redux的store做为props,经过context对象传递给子孙组件上的connect
那connect作了些什么呢?
它真正链接 Redux 和 React,它包在咱们的容器组件的外一层,它接收上面 Provider 提供的 store 里面的 state 和 dispatch,传给一个构造函数,返回一个对象,以属性形式传给咱们的容器组件。
关于它的源码
connect是一个高阶函数,首先传入mapStateToProps、mapDispatchToProps,而后返回一个生产Component的函数(wrapWithConnect),而后再将真正的Component做为参数传入wrapWithConnect,这样就生产出一个通过包裹的Connect组件,该组件具备以下特色:
经过props.store获取祖先Component的store
props包括stateProps、dispatchProps、parentProps,合并在一块儿获得nextState,做为props传给真正的Component
componentDidMount时,添加事件this.store.subscribe(this.handleChange),实现页面交互
shouldComponentUpdate时判断是否有避免进行渲染,提高页面性能,并获得nextState
componentWillUnmount时移除注册的事件this.handleChange
export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
return function wrapWithConnect(WrappedComponent) {
class Connect extends Component {
constructor(props, context) {
// 从祖先Component处得到store
this.store = props.store || context.store
this.stateProps = computeStateProps(this.store, props)
this.dispatchProps = computeDispatchProps(this.store, props)
this.state = { storeState: null }
// 对stateProps、dispatchProps、parentProps进行合并
this.updateState()
}
shouldComponentUpdate(nextProps, nextState) {
// 进行判断,当数据发生改变时,Component从新渲染
if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
this.updateState(nextProps)
return true
}
}
componentDidMount() {
// 改变Component的state
this.store.subscribe(() = {
this.setState({
storeState: this.store.getState()
})
})
}
render() {
// 生成包裹组件Connect
return (
<WrappedComponent {...this.nextState} />
)
}
}
Connect.contextTypes = {
store: storeShape
}
return Connect;
}