React中Connect原理


用法

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM