美文网首页
useState - React源码解析(八)

useState - React源码解析(八)

作者: 请叫我Pro大叔 | 来源:发表于2020-07-11 09:25 被阅读0次

本文将讲解useState钩子的实现。useState是基于useReducer实现的。其reducer函数为:

function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

Mount阶段

useState的这个阶段和useReducer所完成的事情是一样,只是其reducer为basicStateReducer,而useReducer是由参数传入:

  1. useState首先调用mountWorkInProgressHook创建一个Hook对象
  2. 然后,计算初始状态值initialState,该值可以是由第二个参数(当不传第三个参数时)传入,也可由第三个参数(只能是函数)和第二个参数计算所得。
  3. 创建queue以及dispatch函数
  4. 返回初始值initialState以及dispatch函数
function mountState<S>(
  initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
  const hook = mountWorkInProgressHook();
  if (typeof initialState === 'function') {
    // $FlowFixMe: Flow doesn't like mixed types
    initialState = initialState();
  }
  hook.memoizedState = hook.baseState = initialState;
  const queue = (hook.queue = {
    pending: null,
    dispatch: null,
    lastRenderedReducer: basicStateReducer,
    lastRenderedState: (initialState: any),
  });
  const dispatch: Dispatch<
    BasicStateAction<S>,
  > = (queue.dispatch = (dispatchAction.bind(
    null,
    currentlyRenderingFiber,
    queue,
  ): any));
  return [hook.memoizedState, dispatch];
}

Update阶段

这个阶段是直接调用的updateReducer,其逻辑大体与updateReducer相同。

function updateState<S>(
  initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
  return updateReducer(basicStateReducer, (initialState: any));
}

相关文章

网友评论

      本文标题:useState - React源码解析(八)

      本文链接:https://www.haomeiwen.com/subject/lepbcktx.html