There are some points that can be optimized about src/reactCode/ReactFiber.js
- FiberNode 构造函数不完整
function FiberNode(tag, pendingProps, key) { // 基本属性 this.tag = tag; this.key = key; this.type = null; this.stateNode = null;
// Props 相关 this.pendingProps = pendingProps; this.memoizedProps = null;
// State 相关 this.memoizedState = null; this.updateQueue = null;
// Fiber 树结构 this.return = null; this.child = null; this.sibling = null; this.index = 0;
// Effects 相关 this.flags = NoFlags; this.subtreeFlags = NoFlags; this.deletions = null;
// 双缓存相关 this.alternate = null;
// 调度相关 this.lanes = 0; this.childLanes = 0; }
- 类型判断逻辑优化
export function createFiberFromElement(element) { const { key, type, props } = element; let tag;
if (typeof type === 'string') { tag = HostComponent; // 原生 DOM 组件 } else if (typeof type === 'function') { // 需要区分函数组件和类组件 if (type.prototype && type.prototype.isReactComponent) { tag = ClassComponent; // 需要导入 ClassComponent } else { tag = FunctionComponent; } } else if (typeof type === 'object' && type !== null) { // 处理 React.memo, React.forwardRef 等 switch (type.$$typeof) { case REACT_MEMO_TYPE: tag = MemoComponent; break; case REACT_FORWARD_REF_TYPE: tag = ForwardRef; break; // ... 其他情况 } }
const fiber = createFiber(tag, props, key); fiber.type = type; return fiber; }
- 添加参数验证
function createFiber(tag, pendingProps = null, key = null) { if (tag === undefined || tag === null) { throw new Error('Fiber tag cannot be null or undefined'); } return new FiberNode(tag, pendingProps, key); }
- createWorkInProgress 优化
export function createWorkInProgress(current, pendingProps) { let workInProgress = current.alternate;
if (workInProgress === null) { // 首次渲染,创建新的 workInProgress workInProgress = createFiber(current.tag, pendingProps, current.key); workInProgress.type = current.type; workInProgress.stateNode = current.stateNode;
// 建立双向链接
workInProgress.alternate = current;
current.alternate = workInProgress;
} else { // 复用现有的 workInProgress workInProgress.pendingProps = pendingProps; // 重置副作用相关字段 workInProgress.flags = NoFlags; workInProgress.subtreeFlags = NoFlags; workInProgress.deletions = null; }
// 复制不变的属性 workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; workInProgress.updateQueue = current.updateQueue;
// 复制调度相关 workInProgress.lanes = current.lanes; workInProgress.childLanes = current.childLanes;
return workInProgress; }