// 进入 mountState 逻辑
function mountState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
// 将新的 hook 对象追加进链表底部
const hook = mountWorkInProgressHook();
// initialState 可以是一个回调函数,如果是回调,则取回调执行后的值
if (typeof initialState === 'function') {
// $FlowFixMe: Flow doesn't like mixed types
// 对 initialState 重新赋值
initialState = initialState();
}
// memorizedState 存储初始化的 initialState,后期用于记录上次渲染过程中最终获得的 state
hook.memoizedState = hook.baseState = initialState;
// 创建 hook 对象的更新队列,这一步主要是为了能够依序保留 dispatch
const queue = (hook.queue = {
pending: null,
interleaved: null,
lanes: NoLanes,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: (initialState: any),
});
// 由 dispatchAction 方法创建 dispatch,内部更新 queue 的 pending [循环链表]、interleaved、lanes
const dispatch: Dispatch<
BasicStateAction<S>,
> = (queue.dispatch = (dispatchAction.bind(
null,
currentlyRenderingFiber,
queue,
): any));
// 返回目标数组,dispatch 其实就是常见的 setXXX 函数
return [hook.memoizedState, dispatch];
}