-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-4.js
More file actions
84 lines (75 loc) · 1.96 KB
/
example-4.js
File metadata and controls
84 lines (75 loc) · 1.96 KB
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
// 案例 4
const MyReact = (function () {
let hooks = [], // Hook 数组
currentHookIndex = 0 // 记录当前要访问的 Hook 索引
return {
render(Component) {
const Comp = Component()
Comp.render()
currentHookIndex = 0 // 重置索引,为下一次渲染做准备
return Comp
},
useEffect(callback, depArray) {
const hasNoDeps = !depArray
const deps = hooks[currentHookIndex]
const hasChangedDeps = deps
? /* 非首次调用 */ depArray.some((dep, i) => !Object.is(dep, deps[i]))
: /* 首次调用 */true
if (hasNoDeps || hasChangedDeps) {
callback()
hooks[currentHookIndex] = depArray
}
currentHookIndex++
},
useState(initialValue) {
hooks[currentHookIndex] = hooks[currentHookIndex] || initialValue
const setStateHookIndex= currentHookIndex // setState 闭包中使用!
function setState(newVal) {
hooks[setStateHookIndex] = newVal
}
return [hooks[currentHookIndex++], setState]
}
}
})()
// [续] 案例 4
function Counter() {
const [count, setCount] = MyReact.useState(0)
const [text, setText] = MyReact.useState('foo') // 第二个状态 Hook
MyReact.useEffect(() => {
console.log('[effect]', count)
}, [count, text])
return {
click() {
setCount(count + 1)
},
render() {
console.log('[render]', { count, text })
},
noop() {
setCount(count)
},
type(txt) {
setText(txt)
}
}
}
let App
App = MyReact.render(Counter)
// [effect] 0
// [render] { count: 0, text: 'foo' }
App.click()
App = MyReact.render(Counter)
// [effect] 1
// [render] { count: 1, text: 'foo' }
App.type('bar')
App = MyReact.render(Counter)
// [effect] 1
// [render] { count: 1, text: 'bar' }
App.noop()
App = MyReact.render(Counter)
// // no effect run
// [render] { count: 1, text: 'bar' }
App.click()
App = MyReact.render(Counter)
// [effect] 2
// [render] { count: 2, text: 'bar' }