J-DuYa / DY-Book

迁移知识点
2 stars 1 forks source link

React useState源码解析 #10

Open J-DuYa opened 3 years ago

J-DuYa commented 3 years ago

React 之 useState

当我多次被打击的时候,只能想到让自己变得更加的强大,让自己生活下去

首先,我们从什么地方了解 useState 的呢?

const [count, setCount] = useState(null);

在开发中,我们会经常会在函数组件中看到上面的这段类似的代码,那他执行的原理是什么样的呢?

// 在 react源码中的reactHook.js我们看到这样的代码
export function useState<S>(
  initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
  const dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);
}

然后,看到它内部的话调用了resolveDispatcher方法,next step

function resolveDispatcher() {
  const dispatcher = ReactCurrentDispatcher.current;
  if (__DEV__) {
    if (dispatcher === null) {
      console.error(
        'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
          ' one of the following reasons:\n' +
          '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
          '2. You might be breaking the Rules of Hooks\n' +
          '3. You might have more than one copy of React in the same app\n' +
          'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
      );
    }
  }
  // Will result in a null access error if accessed outside render phase. We
  // intentionally don't throw our own error because this is in a hot path.
  // Also helps ensure this is inlined.
  return ((dispatcher: any): Dispatcher);
}

进入这一步之后,看见调用了 ReactCurrentDispatcher.current, 然后,我们进入ReactCurrentDispatcher.js中😄

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;
woow-wu7 commented 3 years ago

???