瞌睡龙

技术杂货铺

0%

使用PureComponent提高render性能

最近在看ant pro 发现一个新奇的东西


这个 PureComponent 是哪里来的呢

什么是PureComponent

PureComponent就是React 15.3.0 新增了一个 PureComponent 类,我们可以以es6的方式方便的定义纯组件。

为什么使用PureComponent

使用PureComponent之后,组件在shoudComponentUpdate中会浅比较渲染前后的props和state,如果没有变化,组件不会进入接下来的生命周期,可以节省不必要的diff操作。
下面举个例子
这里有两个组件,Parent和Child

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
// parent.js
import React, {Component} from 'react';
import Child from './child';

class Parent extends Component {
constructor() {
super();
this.state = {
title: 'title'
};

this.changeState = this.changeState.bind(this);
}

changeState() {
this.state.title = Math.random();
this.setState(this.state);
}

render() {
return (
<div>
<h3>Container</h3>
<button type="button" onClick={this.changeState}>change</button>
<Child></Child>
</div>
);
}

componentWillUpdate() {
console.log('parent will update');
}
}

export default Parent;
// child.js
import React, {Component} from 'react';

class Child extends Component {
render() {
return (
<div>child</div>
);
}

componentWillUpdate() {
console.log('child will update');
}
}

export default Child;
`</pre>

在这里,Child组件没有任何属性输入和state状态,只是一个静态组件,我们点击Parent的change按钮,讲道理Child组件不应该进行任何diff,但是实际情况是"parent will update"和"child will update"都被打印出来了,这是不合理的。所以我们修改下child.js,让它继承PureComponent

<pre class="line-numbers prism-highlight" data-start="1">`//child.js
import React, {PureComponent} from 'react';

class Child extends PureComponent {
render() {
return (
&lt;div&gt;child&lt;/div&gt;
);
}

componentWillUpdate() {
console.log('child will update');
}
}

export default Child;

然后我们再次点击按钮,会发现只输出了”parent will update”,这是我们想要的。

应该注意的问题

PureComponent只能说是一种泛泛的性能问题解决方法,并不具备很高的定制性,最好的方式还是自己去处理组件的shoudComponentUpdate。并且,PureComponent的浅对比shallowEqual在对比引用值的时候,也会存在问题。

欢迎关注我的其它发布渠道