上一篇写了Children,createRef,接着上一篇写后面的几个API
const React = { Children: { map, forEach, count, toArray, only, }, createRef, Component, PureComponent, createContext, forwardRef, lazy, memo, useCallback, useContext, useEffect, useImperativeHandle, useDebugValue, useLayoutEffect, useMemo, useReducer, useRef, useState, Fragment: REACT_FRAGMENT_TYPE, Profiler: REACT_PROFILER_TYPE, StrictMode: REACT_STRICT_MODE_TYPE, Suspense: REACT_SUSPENSE_TYPE, createElement: createElement, cloneElement: cloneElement, createFactory: createFactory, isValidElement: isValidElement, version: ReactVersion, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals, };
const emptyObject = {}; class Component { constructor(props, context, updater) { this.props = props; this.context = context; this.ref = emptyObject; this.updater = updater || null; } isReactComponent() {} setState(partialState, callback) { this.updater.enqueueSetState(this, partialState, callback, "setState"); } forceUpdate(callback) { this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); } }
这里我稍微改了一下源代码,源代码是用的function构造函数,这里我觉的class看着会更简单一些,其实是一摸一样的,Component的源代码在ReactBaseClasses里
并分赋值
补充一下源码中可能用到了ReactNoopUpdateQueue,这个文件只是在dev中使用,仅仅给出一些提示而已
class PureComponent extends Component { constructor(props, context, updater) { super(props, context, updater); this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || null; } isPureReactComponent = true; }
isPureReactComponent = true
import { REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE } from "shared/ReactSymbols"; export function createContext(defaultValue, calculateChangedBits) { if (calculateChangedBits == undefined) { calculateChangedBits = null; } const context = { $$typeof: REACT_CONTEXT_TYPE, _calculateChangedBits: calculateChangedBits, _currentValue: defaultValue, _currentValue2: defaultValue, _threadCount: 0, Provider: null, Consumer: null }; (context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }), (context.Consumer = context); return context; }
import { REACT_FORWARD_REF_TYPE } from "shared/ReactSymbols"; export default function forwardRef(render) { return { $$typeof: REACT_FORWARD_REF_TYPE, render }; }
可能很多人看了很疑惑,感觉看完也没什么用,但这就是一个看react源码的逻辑,不要一开始就过分追求从到到尾的实现,因为react代码很多很多,我觉得一层一层的往里看是比较好的方法,等看完这些,到了react-dom内容的时候,慢慢的就会发现这些API里面的属性它到底是做什么用的了。
累了明天再写吧