useState

react对useState进行了封装,调用了mountState。

function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
currentHookNameInDev = 'useState';
mountHookTypesDev();
const prevDispatcher = ReactCurrentDispatcher.current;
ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher.current = prevDispatcher;
}
}

mountState

如果initialState是函数还可以执行。

生成一个dispatch方法,通过闭包绑定当前states。

把初始值存到memoizedState上。这个memoizedState绑定到fiber树上。用来存储state。

function mountState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
// 把hooks加入queue,实际上是为了保证执行顺序。
const hook = mountWorkInProgressHook();
if (typeof initialState === 'function') {
initialState = initialState();
}
hook.memoizedState = hook.baseState = initialState;
const queue = (hook.queue = {
last: null,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: (initialState: any),
});
const dispatch: Dispatch<
BasicStateAction<S>,
> = (queue.dispatch = (dispatchAction.bind(
null,
// Flow doesn't know this is non-null, but we do.
((currentlyRenderingFiber: any): Fiber),
queue,
): any));
return [hook.memoizedState, dispatch];
}

memoizedState

react其实不知道我们调用了几次useState。

所以还是在memoizedState上动手脚,这个处理体现在mountWorkInProgressHook

 memoizedState: {
baseState,
next,
baseUpdate,
queue,
memoizedState
}

memoizedState.next就是下一次useState的hook对象。

hook1 === Fiber.memoizedState
state1 === hook1.memoizedState
state2 = hook1.next.memoizedState

因为以这种方式存储,所以usestate必须在functionalComponent的根作用域中。不能被for,和if。

setstate

mountState函数返回的是 return [hook.memoizedState, dispatch];

dispatch通过闭包就可以处理state。

更新

useState在更新的时候是调用的updateState,这个函数其实是封装的updateReducer。

function renderWithHooks(){
ReactCurrentDispatcher.current =
nextCurrentHook === null
? HooksDispatcherOnMount
: HooksDispatcherOnUpdate;
};
HooksDispatcherOnMount: {
useState: mountState,
}
HooksDispatcherOnUpdate: {
useState: updateState,
}

updateReducer

可以看到updateReducer把新的fiber中的state值更新,返回新的值。然后后续走渲染流程。(之前写过reat 的渲染流程)

还可以看到这有个循环update = update.next; while (update !== null && update !== first);

这就是hooks的batchUpdate。

function updateReducer<S, I, A>(
reducer: (S, A) => S,
initialArg: I,
init?: I => S,
): [S, Dispatch<A>] {
const hook = updateWorkInProgressHook();
const queue = hook.queue; queue.lastRenderedReducer = reducer; // ...
// The last update in the entire queue
const last = queue.last;
// The last update that is part of the base state.
const baseUpdate = hook.baseUpdate;
const baseState = hook.baseState; // Find the first unprocessed update.
let first;
if (baseUpdate !== null) {
if (last !== null) {
// For the first update, the queue is a circular linked list where
// `queue.last.next = queue.first`. Once the first update commits, and
// the `baseUpdate` is no longer empty, we can unravel the list.
last.next = null;
}
first = baseUpdate.next;
} else {
first = last !== null ? last.next : null;
}
if (first !== null) {
let newState = baseState;
let newBaseState = null;
let newBaseUpdate = null;
let prevUpdate = baseUpdate;
let update = first;
let didSkip = false;
do {
const updateExpirationTime = update.expirationTime;
if (updateExpirationTime < renderExpirationTime) {
// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
if (!didSkip) {
didSkip = true;
newBaseUpdate = prevUpdate;
newBaseState = newState;
}
// Update the remaining priority in the queue.
if (updateExpirationTime > remainingExpirationTime) {
remainingExpirationTime = updateExpirationTime;
}
} else {
markRenderEventTimeAndConfig(
updateExpirationTime,
update.suspenseConfig,
); // 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);
}
}
prevUpdate = update;
update = update.next;
} while (update !== null && update !== first); if (!didSkip) {
newBaseUpdate = prevUpdate;
newBaseState = newState;
} // 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.baseUpdate = newBaseUpdate;
hook.baseState = newBaseState; queue.lastRenderedState = newState;
} const dispatch: Dispatch<A> = (queue.dispatch: any);
return [hook.memoizedState, dispatch];
}

react 16 Hooks渲染流程的更多相关文章

  1. react 16 ssr的重构踩坑

    ssr 服务端不能识别前端的window.特别是首屏渲染的数据需要用到window对象(比如href += location.search); 服务端不能加载图片,css文件. require.ext ...

  2. react 16 渲染整理

    背景 老的react架构在渲染时会有一些性能问题,从setstate到render,程序一直在跑,一直到render完成.才能继续下一步操作.如果组件比较多,或者有复杂的计算逻辑,这之间的消耗的时间是 ...

  3. React 16.x & Hooks

    React 16.x & Hooks Hooks https://reactjs.org/docs/hooks-intro.html https://reactjs.org/docs/hook ...

  4. React 16 服务端渲染的新特性

    React 16 服务端渲染的新特性 React 16 中关于服务端渲染的新特性 快速介绍React 16 服务端渲染的新特性,包括数组.性能.流等 React 16 终于来了!

  5. react16 渲染流程

    前言 react升级到16之后,架构发生了比较大的变化,现在不看,以后怕是看不懂了,react源码看起来也很麻烦,也有很多不理解的地方. 大体看了一下渲染过程. react16架构的变化 react ...

  6. react 使用hooks

    react hooks文档 λ yarn add react@16.7.0-alpha.2 λ yarn add react-dom@16.7.0-alpha.2 设置 state import Re ...

  7. [译] React 16.3(.0-alpha) 新特性

    原文地址:What's new in React 16.3(.0-alpha) 原文作者:Bartosz Szczeciński 译文出自:掘金翻译计划 本文永久链接:github.com/xitu/ ...

  8. react 16.8版本新特性以及对react开发的影响

    Facebook团队对社区上的MVC框架都不太满意的情况下,开发了一套开源的前端框架react,于2013年发布第一个版本. react最开始倡导函数式编程,使用function以及内部方法React ...

  9. cocos2d-x渲染流程

    Cocos2Dx之渲染流程 发表于8个月前(2014-08-08 22:46)   阅读(3762) | 评论(2) 17人收藏此文章, 我要收藏 赞2 如何快速提高你的薪资?-实力拍“跳槽吧兄弟”梦 ...

随机推荐

  1. 使用Redis作为Spring Security OAuth2的token存储

    写在前边 本文对Spring Security OAuth2的token使用Redis保存,相比JWT实现的token存储,Redis可以随时吊销access_token,并且Redis响应速度很快, ...

  2. 夜神模拟器怎么连接adb

    夜神模拟器连接不了adb的原因主要是adb的版本与夜神模拟器adb版本不一致造成的,具体的解决办法请看下面的操作步骤. 工具/原料   电脑 安装了夜神模拟器 方法/步骤   1 使用快捷键win + ...

  3. Python【day 13】内置函数01

    1.python3.6.2 一共有 68个内置函数2.分成6个大类 1.反射相关-4个 2.面向对象相关-9个 3.作用域相关--2个 1.globlas() #注意:最后是s,复数形式 查看全局作用 ...

  4. webpack4 babel 篇

    demo 代码点此,如果对 babel 不熟,可以看一下babel 7 简单指北. webpack 使用 babel 来打包使用 es6 及以上语法的 js 文件是非常方便的,可以通过配置,将 es6 ...

  5. Vue实战狗尾草博客管理系统第一章

    Vue实战狗尾草博客后台管理系统第一章 这里准备采用的技术栈为:vue全家桶+element-ui 这里因为是后台管理系统,没有做SSR的必要.所以这里就采用前后端分离来昨晚这个项目~ 项目搭建 vu ...

  6. HeadFirst设计模式---简单工厂

    简单工厂的理解 简单工厂不是设计模式的一种,只是代码规范而且.也就是说构造一个披萨工厂出来,按不同味道生产不同的披萨. 类图 抽象披萨 public abstract class AbstractPi ...

  7. HeadFirst设计模式---装饰者

    定义装饰者模式 装饰者模式动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案.这句话摘自书中,给人读得很生硬难懂.通俗地来说,装饰者和被装饰者有相同的父类,装饰者的行为组装着 ...

  8. Vue+ElementUI 安装与应用

    1.初始化创建一个vue项目: 打开终端输入命令 vue init webpack vueui ---------------------------------- ? Project name my ...

  9. SpringBoot的学习二:整合Redis,JPA,Mybatis

    Redis介绍: 是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API 特性: Redis 与其他 key - value 缓 ...

  10. 设置VMware中Kali 共享文件夹

    (软件环境: Vmware Workstation 15.5 Pro , Kali Linux2019.3) 1. VMware设置共享目录 2. 安装VMware-Tools 命令: apt-get ...