-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-4.1.js
More file actions
66 lines (55 loc) · 1.58 KB
/
example-4.1.js
File metadata and controls
66 lines (55 loc) · 1.58 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
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.1
function Component() {
const [text, setText] = useSplitURL('www.netlify.com')
return {
type(txt) {
setText(txt)
},
render() {
console.log('[render]', { text })
}
}
}
function useSplitURL(str) {
const [text, setText] = MyReact.useState(str)
const masked = text.split('.')
return [masked, setText]
}
let App
App = MyReact.render(Component)
// [render] { text: [ 'www', 'netlify', 'com' ] }
App.type('www.reactjs.org')
App = MyReact.render(Component)
// [render] { text: [ 'www', 'reactjs', 'org' ] }