-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLv04_useCallback.js
More file actions
51 lines (45 loc) · 1.18 KB
/
Copy pathLv04_useCallback.js
File metadata and controls
51 lines (45 loc) · 1.18 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
import React, { useState, memo, useCallback } from 'react';
import { isEqual } from 'lodash';
const Foo = memo(
function Foo(props) {
console.log('Lv04_useCallback: Foo render');
return (
<>
<h1>{props.name}</h1>
</>
);
},
function (prevProps, nextProps) {
let propsIsEqual = true;
for (let key in prevProps.person) {
propsIsEqual = isEqual(prevProps[key], nextProps[key]);
}
return propsIsEqual;
}
);
const Bar = memo(function Bar(props) {
console.log(`Lv04_useCallback: ${props.name} render`);
return (
<>
<h1>{props.name}</h1>
</>
);
});
export default function Demo4() {
const [title, setTitle] = useState(0);
const callback = () => {
setTitle(new Date().getTime());
};
const callbackUseHook = useCallback(() => {
setTitle(new Date().getTime());
}, []);
return (
<div className="App">
<h1>主标题:{title}</h1>
<button onClick={() => setTitle(new Date().getTime())}>改副标题</button>
<Foo onClick={callback} name="Richard" />
<Bar num={1} onClick={callback} name="Richard1" />
<Bar num={2} onClick={callbackUseHook} name="Richard2" />
</div>
);
}