useState源码解读 及 手撕 useState 实现
创始人
2024-03-20 05:03:25
0

文章目录

  • useState源码解读 及 手撕 useState 实现
    • useState源码分析
      • 逻辑图
      • 源码解读
        • mountState
          • mountWorkInProgressHook 函数
        • updateState
          • updateReducer 函数
    • 实现
    • 对比图
    • 实现效果
      • 只声明一个 hook
      • 重复调用同一个 hook
      • 声明多个不同的 hooks
    • 体验收获

useState源码解读 及 手撕 useState 实现

useState源码分析

逻辑图

在这里插入图片描述

源码解读

hooks 保存在 packages/react-reconciler/src/ReactFiberHooks.old.js 文件中

有一个 dispatcher 的数据结构,是个对象,在不同的 dispatcher 中,都同样存在了 useState;

在不同的 dispatcher 中,useState 的实现对应的是不同的方法:

即 useState 在不同的上下文中对应的是不同的函数
所以:react 通过在不同的上下文使用不同的 dispatcher,来区分当前需要使用 hooks 的不同实现

比如:
在这里插入图片描述

mountState

首先看 mountState 的实现:

  1. 调用 mountWorkInProgressHook 创建hook对象
  2. 初始化 memoizedState 和 baseState ,值为 initialState
  3. 创建 hook 的 updateQueue
  4. 创建 dispatch 方法(其实就是 绑定了当前的 fiber和 queue 的 dispatchAction )

在这里插入图片描述

mountWorkInProgressHook 函数
  1. 创建一个 hook 对象
  2. 若这是第一个 hook,挂载到 memoizedState
  3. 若不是第一个hook的话,就会把他挂载到上一个 hook的 next 指针下,与上一个hook形成一条链表
  4. 返回 该hook 对象

在这里插入图片描述

updateState

在这里插入图片描述

其实,useState 就是一个预置了 reducer 的 useReducer,预置的 reducer 就是 basicStateReducer

在这里插入图片描述

updateReducer 函数

总结:首先获取当前 hooks和 当前的 queue,之后就会 根据 baseState 和 拥有优先级 的 update来计算 memoizedState

具体代码在这:

function updateReducer(reducer: (S, A) => S,initialArg: I,init?: I => S,
): [S, Dispatch] {const hook = updateWorkInProgressHook();const queue = hook.queue;invariant(queue !== null,'Should have a queue. This is likely a bug in React. Please file an issue.',);queue.lastRenderedReducer = reducer;const current: Hook = (currentHook: any);// The last rebase update that is NOT part of the base state.let baseQueue = current.baseQueue;// The last pending update that hasn't been processed yet.const pendingQueue = queue.pending;if (pendingQueue !== null) {// We have new updates that haven't been processed yet.// We'll add them to the base queue.if (baseQueue !== null) {// Merge the pending queue and the base queue.const baseFirst = baseQueue.next;const pendingFirst = pendingQueue.next;baseQueue.next = pendingFirst;pendingQueue.next = baseFirst;}if (__DEV__) {if (current.baseQueue !== baseQueue) {// Internal invariant that should never happen, but feasibly could in// the future if we implement resuming, or some form of that.console.error('Internal error: Expected work-in-progress queue to be a clone. ' +'This is a bug in React.',);}}current.baseQueue = baseQueue = pendingQueue;queue.pending = null;}if (baseQueue !== null) {// We have a queue to process.const first = baseQueue.next;let newState = current.baseState;let newBaseState = null;let newBaseQueueFirst = null;let newBaseQueueLast = null;let update = first;do {const updateLane = update.lane;if (!isSubsetOfLanes(renderLanes, updateLane)) {// Priority is insufficient. Skip this update. If this is the first// skipped update, the previous update/state is the new base// update/state.const clone: Update = {lane: updateLane,action: update.action,eagerReducer: update.eagerReducer,eagerState: update.eagerState,next: (null: any),};if (newBaseQueueLast === null) {newBaseQueueFirst = newBaseQueueLast = clone;newBaseState = newState;} else {newBaseQueueLast = newBaseQueueLast.next = clone;}// Update the remaining priority in the queue.// TODO: Don't need to accumulate this. Instead, we can remove// renderLanes from the original lanes.currentlyRenderingFiber.lanes = mergeLanes(currentlyRenderingFiber.lanes,updateLane,);markSkippedUpdateLanes(updateLane);} else {// This update does have sufficient priority.if (newBaseQueueLast !== null) {const clone: Update = {// This update is going to be committed so we never want uncommit// it. Using NoLane works because 0 is a subset of all bitmasks, so// this will never be skipped by the check above.lane: NoLane,action: update.action,eagerReducer: update.eagerReducer,eagerState: update.eagerState,next: (null: any),};newBaseQueueLast = newBaseQueueLast.next = clone;}// Process this update.if (update.eagerReducer === reducer) {// If this update was processed eagerly, and its reducer matches the// current reducer, we can use the eagerly computed state.newState = ((update.eagerState: any): S);} else {const action = update.action;newState = reducer(newState, action);}}update = update.next;} while (update !== null && update !== first);if (newBaseQueueLast === null) {newBaseState = newState;} else {newBaseQueueLast.next = (newBaseQueueFirst: any);}// Mark that the fiber performed work, but only if the new state is// different from the current state.if (!is(newState, hook.memoizedState)) {markWorkInProgressReceivedUpdate();}hook.memoizedState = newState;hook.baseState = newBaseState;hook.baseQueue = newBaseQueueLast;queue.lastRenderedState = newState;}const dispatch: Dispatch = (queue.dispatch: any);return [hook.memoizedState, dispatch];
}

查阅各种文档资料视频等,勉勉强强的弄懂了 useState 的实现原理,今天来简单实现一下 useState,思路都在 代码注释中:

实现


Document


对比图

在这里插入图片描述

在这里插入图片描述

实现效果

只声明一个 hook

在这里插入图片描述

在这里插入图片描述

重复调用同一个 hook

在这里插入图片描述

在这里插入图片描述

声明多个不同的 hooks

在这里插入图片描述

在这里插入图片描述

体验收获

源码确实很难,需要花很多时间,但是弄懂了之后,很有成就感,也觉得 react 没有那么神秘了,加油!

相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...
群晖外网访问终极解决方法:IP... 写在前面的话 受够了群晖的quickconnet的小水管了,急需一个新的解决方法&#x...