Appearance
useCallback
useCallback 用于得到一个固定引用值的函数,通常用它进行性能优化!
JavaScript
import React, { useState, useCallback, memo } from "react";
class Child1 extends React.PureComponent {
render() {
console.log('child1 render');
return <div>
<button onClick={this.props.handler}>处理1</button>
</div>;
}
}
/* class Child2 extends React.PureComponent {
render() {
console.log('child2 render');
return <div>
<button onClick={this.props.handler}>处理2</button>
</div>;
}
} */
// 如果子组件是函数组件,则需要useCallback和memo配合使用「函数组件的属性浅比较是在memo中处理的,类组件是在shouldComponentUpdate中」
const Child2 = memo(function Child2({ handler }) {
console.log('child2 render');
return <div>
<button onClick={handler}>处理2</button>
</div>;
});
export default function Demo() {
let [val, setVal] = useState('');
const handler1 = () => {
setVal('哈哈哈');
};
const handler2 = useCallback(() => {
setVal('呵呵呵');
}, []);
return <div>
<input type="text" value={val}
onChange={ev => {
setVal(ev.target.value);
}} />
<Child1 handler={handler1} />
<Child2 handler={handler2} />
</div>;
};
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
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