-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.js
More file actions
62 lines (59 loc) · 1.49 KB
/
Copy pathhooks.js
File metadata and controls
62 lines (59 loc) · 1.49 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
const React = (() => {
let hooks = [];
let index = 0;
function useState(initVal) {
let state = hooks[index] || initVal;
let _index = index;
let setState = (newVal) => {
hooks[_index] = newVal;
};
index++;
return [state, setState];
}
function useRef(val) {
return useState({ current: val })[0];
}
function useEffect(cb, depArray) {
const oldDeps = hooks[index];
let hasChanged = true;
if (oldDeps) {
hasChanged = depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
}
if (hasChanged) {
cb();
}
hooks[index] = depArray;
}
function render(component) {
index = 0;
const c = component();
c.render();
return c;
}
return { useState, useEffect, useRef, render };
})();
function Component() {
const [count, setCount] = React.useState(1);
const [text, setText] = React.useState("Test");
const ref = React.useRef(1);
React.useEffect(() => {
console.log("effect test");
}, [text]);
return {
render: () => {
console.log(ref.current);
console.log({ count, text });
},
click: () => {
setCount(count + 1);
},
type: (word) => {
setText(word);
},
};
}
var app = React.render(Component);
app.click();
app = React.render(Component);
app.type("vue");
app = React.render(Component);