-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
120 lines (108 loc) · 3.81 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let isMount = true; // 用来标记是首次渲染还是更新
let workInProgressHook = null; // 保存当前执行的hook
const fiber = {
memoizedState: null, // 用来保存需要执行的 hooks
stateNode: App, // 保存对应的组件
};
function run() {
// hook初始化
workInProgressHook = fiber.memoizedState;
// render阶段
const app = fiber.stateNode();
// commit阶段
isMount = false;
return app;
}
// 创建 update,并形成环状链表
function dispatchAction(queue, action) {
// 创建 update
const xAction = typeof action === 'function' ? action : () => action;
const update = {
action: xAction,
next: null,
};
if (queue.pending === null) {
update.next = update;
} else {
// 3 -> 0 -> 1 -> 2 -> 3
// 4 -> 0 -> 1 -> 2 -> 3 -> 4
// queue.pending.next 第一个
// queue.pending 最后一个
// 把 update 放到前面,也就是 4->0的过程
update.next = queue.pending.next;
// 在最后在加上 update,也就是3->4的过程
queue.pending.next = update;
}
// 构成的新环给挂载到 queue 上去
queue.pending = update;
run();
}
function useState(initState) {
let hook;
if (isMount) {
hook = {
queue: {
pending: null,
},
memoizedState:
typeof initState === 'function' ? initState() : initState,
next: null,
};
// 判断fiber上是否存在hook未执行,如果不存在就把新建的放上去
if (!fiber.memoizedState) {
fiber.memoizedState = hook;
} else {
// 如果存在就拼在后面
fiber.memoizedState.next = hook;
}
// 保存当前的hook;
workInProgressHook = hook;
} else {
// 如果在更新阶段,取出当前需要执行的hook
hook = workInProgressHook;
workInProgressHook = workInProgressHook.next;
}
let baseState = hook.memoizedState;
if (hook.queue.pending) {
// 如果存在代表有需要执行的hook
let firstUpdate = hook.queue.pending.next;
do {
const action = firstUpdate.action; // 取出useState的方法,react里的useState可以传入两种:值和函数,这里简化了,只支持传入函数
baseState = action(baseState); //计算出新的baseState
firstUpdate = firstUpdate.next;
} while (firstUpdate !== hook.queue.pending.next); // 直到它不等于第一个 update 为止,因为这个地方是个环。
hook.queue.pending = null; //计算完了
}
hook.memoizedState = baseState;
return [baseState, dispatchAction.bind(null, hook.queue)];
}
function App() {
const [num, setNum] = useState(0);
const [status, toggleStatus] = useState(false);
console.log('isMounted?', isMount);
console.log('num:', num);
console.log('status', status);
// 为了足够简单,不返回jsx,直接返回一个对象来模拟组件被点击的效果
return {
onClick() {
setNum((num) => num + 1);
},
toggleStatus() {
toggleStatus((status) => !status);
},
};
}
window.app = run();
</script>
</body>
</html>