用法
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;
}