本文基本react18.3.1
一、useState
useState是在函数组件里调用,而函数组件又是在renderWithHooks里被调用,所以从renderWithHooks开始看应该是个合理的开始。
renderWithHooks的大致流程如下:
1,重置或根据参数设置各种变量;
2,根据current判断当前是是更新(current !== null && current.memoizedState !== null)还是首次渲染,设置对应的HooksDispatcher(ReactCurrentDispatcher$1.current),该对象的不同值(HooksDispatcherOnMountWithHookTypesInDEV或HooksDispatcherOnMountInDEV)里的useState执行逻辑不同,详细逻辑见下图;
3,调用函数组件,组件里调用useState就是执行HooksDispatcher.useState,调用逻辑如下图1;如果函数组件里有调用useState返回的set函数(dispatchSetState),设置didScheduleRenderPhaseUpdateDuringThisPass为true;
4,如果didScheduleRenderPhaseUpdateDuringThisPass为true,设置HooksDispatcher为HooksDispatcherOnRerenderInDEV,并执行函数组件
5,重置各种变量,并返回函数组件生成的element对象,用于下一步生成子fiberNode
dispatchSetState
dispatchSetState的执行逻辑大致如下: