forked from wuyawei/fe-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.html
More file actions
81 lines (81 loc) · 3.04 KB
/
Copy pathhooks.html
File metadata and controls
81 lines (81 loc) · 3.04 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="name"></div>
<div class="number"></div>
<button class="add">add</button>
<button class="increment">increment</button>
<span id="count"></span>
</body>
<!-- https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-react-hooks-really-work/ -->
<!-- https://overreacted.io/zh-hans/a-complete-guide-to-useeffect/ -->
<!--https://overreacted.io/zh-hans/react-as-a-ui-runtime/-->
<!-- https://github.com/brickspert/blog/issues/26 -->
<!-- https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e -->
<!-- https://github.com/facebook/react/blob/master/packages/react-reconciler/src/ReactFiberHooks.js -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="./hooks.js"></script>
<script>
// useState/useEffect/useCallback/useReducer/useMemo
const {Tick, useState, useEffect, useReducer, useMemo, useCallback} = hooks;
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return {total: state.total + 1};
case 'decrement':
return {total: state.total - 1};
default:
throw new Error();
}
}
function render() {
const [count, setCount] = useState(0);
useEffect(() => {
// 清除副作用、支持回调
const time = setInterval(() => {
setCount(count => count + 1);
}, 1000)
return () => {
clearInterval(time);
}
}, [count]);
// const [name, setName] = useState(() => 'hi');
// $('.add').on('click', () => { // 重新绑定需要解绑之前的
// setCount(count + 1);
// })
// const [{total}, dispatch] = useReducer(reducer, {total: 0});
// const add = useMemo(() => count + 1, [count]);
// const increment = useCallback(() => {
// setCount(count + 1);
// setName(name + 'ha');
// }, [count, name])
console.log(666);
// $('.add')[0].onclick = () => { // 重复绑定会覆盖之前的
// // 现在触发多次set,不会重渲染多次
// // dispatch({type: 'increment'});
// // setCount(count + 1);
// // setCount(count + 1);
// // setCount(count + 1);
// // setCount(count + 1);
// setCount(count + 1);
// setName(name + 'ha');
// };
document.querySelector('.add').onclick = () => {
setCount(count + 1);
};
document.querySelector('#count').innerHTML = count;
// $('.increment')[0].onclick = increment;
// $('#count').html(count);
// $('.number').html(add);
// $('.name').html(name);
}
Tick.render = render;
render();
</script>
</html>