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. KVM学习笔记--静态迁移

    .静态迁移过程如下 (1)确定虚拟机关闭状态 (2)准备迁移oeltest02虚拟机,查看该虚拟机配置的磁盘文件 (3)导入虚拟机配置文件 [root@node1~]# virsh dumpxml o ...

  2. 在Linux系统中运行并简单的测试RabbitMq容器

    以前使用的是Windows下面的RabbitMq,需要先安装 Erlang的语言环境等,这次直接在Linux中的Docker容器来测试一下 1:docker配置RabbitMq的指令 docker r ...

  3. Docker Desktop for Windows 安装步骤

    Docker Desktop for Windows 安装要求 Docker Desktop for Windows需要运行Microsoft Hyper-V.如果需要,Docker Desktop ...

  4. ucoreOS_lab1 实验报告

    由于我个人不太懂 AT&T 语法,在完成实验的过程中遇到了相当大的阻碍,甚至有点怀疑人生,我是否心太大了,妄想在短时间内学懂大清的课程.ucoreOS_lab1 这个实验前前后后做到了现在才勉 ...

  5. 北京地铁出行线路规划系统项目总结(Java+Flask+Vue实现)

    北京地铁出行线路规划系统项目总结 GitHub仓库地址:https://github.com/KeadinZhou/SE-Subway Demo地址:http://10.66.2.161:8080/ ...

  6. C# 测试网络速度例子

    using System.Net.NetworkInformation; namespace PingExample { public partial class Form1 : Form { pub ...

  7. Java代码实现定时器

    一 import java.util.Timer; import java.util.TimerTask; public class time { public static void main(St ...

  8. python之便携式mysql类和tornado mysql长链接

    mymysql.py class MyMysql2(object): def __init__(self, host = '', user = '', passwd = '', db = '', po ...

  9. SpringBoot整合Fastdfs,实现图片上传(IDEA)

    我们部署Fastdfs,就是为了实现文件的上传. 现在使用idea整合Fastdfs,实现图片上传 部署环境:Centos7部署分布式文件存储(Fastdfs) 利用Java客户端调用FastDFS ...

  10. ulimit 更改 gcc升级 查看显卡状态命令

    一.更改ulimit: vim /etc/security/limits.conf 在文件最下方添加以下内容 * soft nofile 65536* hard nofile 65536 二. gcc ...