react-redux 学习笔记(三)connect API 原理分析

293 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

系列文章

react-redux 学习笔记(一)Provider
react-redux 学习笔记(二)connect 用法
react-redux 学习笔记(三)connect API 原理分析

回顾

react-redux 由两部分构成:Provider 和 connect,Provider 负责将 store 传递给内部所有组件,connect 负责注册监听器,在每一次状态变更之后把新的状态和 action 等作为属性挂到容器组件的 this.props 下。

connect 原理

接上一篇文章,我们下面对 connect 的原理进行解析~

  1. 在 constructor 取得当前的 store 树,可以通过 this.props.store 和 this.context.store 两种方式获取,其中第二种方式是从 Provider 的 getChildContext() 传进来的。
  2. 在 render 里使用 React 的 createElement方法生成新的组件,并将传入的 state 和 action 合并到 props 上。
render(){
    this.renderedElement = createElement(WrappedComponent,
       this.mergedProps //merge stateProps, dispatchProps, props
    )
    return this.renderedElement;
 }

最后返回的时候用hoistNonReactStatic将原来组件中的元素拷贝到目标组件。

hoistNonReactStatic(targetComponent, sourceComponent);
  1. 在 componentDidMount 中使用 store 的 subscribe 方法注册监听事件,以便在 dispatch 之后调用,componentWillUnmount 执行 unsubcribe 事件,注销监听器。
trySubscribe() {
  if (shouldSubscribe && !this.unsubscribe) {
    this.unsubscribe = this.store.subscribe(this.handleChange.bind(this))
    this.handleChange()
  }
}

tryUnsubscribe() {
  if (this.unsubscribe) {
    this.unsubscribe()
    this.unsubscribe = null
  }
}

这样,在每次 dispatch(action) 之后会执行 handleChange,在 handleChange 函数内部,会执行 setState 更新 store tree。

所以每次 dispatch(action) 之后,执行对应的 reducer,然后执行相应的订阅的函数。在 reducer 里把 store 更新,在监听函数里执行 setState,更新 React 组件。

以上时本文全部内容,欢迎点赞和评论~