作者:大爱走钢索的人_738 | 来源:互联网 | 2024-10-23 10:28
总结:
React-redux最外层都会用Provider包裹,如下

在执行connect(mapStateToProps, mapDispatchToProps)(App)时候生成的组建也会再次被Provider再包裹一层,然后执行mapStateToProps, mapDispatchToProps的返回值都会通过Props传递给组建。
connect(mapStateToProps, mapDispatchToProps)(App)等于执行wrapWithConnect方法


先判断 wrapWithConnect方法的入参必须是一个ElementType类型,否则抛出错误。
在生成组建,组建还没有被渲染时候不会执行ConnectFunction。只有当Connect被渲染时候才会执行ConnectFunction方法。也就是connect(mapStateToProps)(App)执行完毕也不会执行ConnectFunction方法。export default connect(mapStateToProps, mapDispatchToProps)(App)第一次生成组建到这里直接就执行完毕,返货hoistStatics函数处理结果,Connect可以被当作组件渲染。当Connect被当作组件渲染时候,才会去执行ConnectFunction方法。

所以会先执行Provider.js 再执行App内部函数也就是ConnectFunction方法。
const COnnect= pure ? React.memo(ConnectFunction) : ConnectFunction
渲染组件执行ConnectFunction方法
因为Provider为顶层组件,所以先执行Provider.js再执行ConnectFunction方法(connect(mapStateToProps)(App)会在Provider.js之前,Provider.js只有在渲染时候执行)
又因为

useIsomorphicLayoutEffect=useLayoutEffect
这块代码是在useLayoutEffect里面执行,所以 ConnectFunction方法比它先执行。
pure默认为true,所以主要看React.memo(ConnectFunction)
ConnectFunction方法有一个props入参,刚开始这个props为空对象。

所以得到的propsCOntext=undefined reactReduxForwardedRef=undefined wrapperProps={}.

propsCOntext=undefined所以 COntextToUse=Context

该Context就是Provider组建里面生成的那个Context
const cOntextValue= useContext(ContextToUse)等于const cOntextValue= useContext(Context)

contextValue对象如上。
显然const didStoreComeFromProps=false;onst didStoreComeFromCOntext=true。
const store = didStoreComeFromProps ? props.store : contextValue.store
等于 const store =contextValue.store (这个store由createStore生产的store对象)
执行createChildSelector(store)等于执行selectorFactory(store.dispatch, selectorFactoryOptions)


initMapStateToProps, initMapDispatchToProps, initMergeProps是不是很熟悉,这个在conconnect.js解析的文章里面有说过。React-redux源码解析--connect.js_跑跑快跑的博客-CSDN博客React-redux源码解析--connect.js
https://blog.csdn.net/qq_33715850/article/details/122555688const selectorFactory=pureFinalPropsSelectorFactory
执行pureFinalPropsSelectorFactory返回结果
pureFinalPropsSelectorFactory返回pureFinalPropsSelector方法
shouldHandleStateChanges=true;

这里执行 createSubscription,这是第一次执行createSubscription,
入参store, parentSub,parentSub为Provider.js生成的subscription,生成一个新的subscription对象。
返回 subscription, notifyNestedSubs。
overriddenContextValue为subscription值为上面新生成的值。

执行childPropsSelector(store.getState(), wrapperProps)相当于执行

这里的mapStateToProps是不是很熟悉,在解析connect时候讲过,然后执行



再此执行就会执行connect(mapStateToProps, mapDispatchToProps)(App)传入的mapStateToProps函数, 并且返回该函数的结果。如果mapStateToProps返回的是一个函数,那么继续执行
proxy.mapToProps = props
proxy.dependsOnOwnProps= getDependsOnOwnProps(props)
props = proxy(stateOrDispatch, ownProps)
最后返回props,也就是执行mapStateToProps函数的结果。最后返回的props必须是一个对象,否则会报错。
同理

dispatchProps也是一样。
最后返回mergedProps赋值给actualChildProps 。最后actualChildProps会通过props全部传递给组件。

最后组件被ContextToUse.Provider包裹返回。
也就是通过 connect(mapStateToProps, mapDispatchToProps)(App)生成的组件都会被
{renderedWrappedComponent}
其中

。