React hook 源码学习

可以在react.js 中看到导入的代码

import {

useCallback,

useContext,

useEffect,

useImperativeHandle,

useDebugValue,

useLayoutEffect,

useMemo,

useMutableSource,

useReducer,

useRef,

useState,

useResponder,

useTransition,

useDeferredValue,

useOpaqueIdentifier,

} from './ReactHooks';

ReactHooks

ReactHooks 里面定义了各个 hooks, 大致内容是如下这样的:

function resolveDispatcher() {
  const dispatcher = ReactCurrentDispatcher.current;

  return dispatcher;
}


export function useState(
  initialState: (() => S) | S,
): [S, Dispatch>] {
  const dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}

export function useReducer(
  reducer: (S, A) => S,
  initialArg: I,
  init?: I => S,
): [S, Dispatch] {
  const dispatcher = resolveDispatcher();
  return dispatcher.useReducer(reducer, initialArg, init);
}

export function useRef(initialValue: T): {|current: T|} {
  const dispatcher = resolveDispatcher();
  return dispatcher.useRef(initialValue);
}

export function useEffect(
  create: () => (() => void) | void,
  deps: Array | void | null,
): void {
  const dispatcher = resolveDispatcher();
  return dispatcher.useEffect(create, deps);
}

他们都通过 ReactCurrentDispatcher.current 去调用函数实现

Dispatcher

ReactCurrentDispatcher


/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Dispatcher} from 'react-reconciler/src/ReactInternalTypes';

/**
 * Keeps track of the current dispatcher.
 */
const ReactCurrentDispatcher = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: (null: null | Dispatcher),
};

export default ReactCurrentDispatcher;

dispatcher 对象

https://github.com/facebook/r...

源码引进门了,大家可以自己调试代码查看理解

你可能感兴趣的:(react.js,hook,hooks)