前言

React15.3中新加了一个 PureComponent 类,PureComponent 也就是纯组件,取代其前身 PureRenderMixin ,

PureComponent 是优化 React 应用程序最重要的方法之一,易于实施,只要把继承类从 Component 换成 PureComponent 即可,可以减少不必要的 render操作的次数,从而提高性能,而且可以少写 shouldComponentUpdate 函数,节省了点代码。但是也有坑要注意

原理

当组件更新时,如果组件的 props 和 state 都没发生改变, render 方法就不会触发,省去 Virtual DOM 的生成和比对过程,达到提升性能的目的。具体就是 React 自动帮我们做了一层浅比较:

if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps)
|| !shallowEqual(inst.state, nextState);
}

shallowEqual会比较 Object.keys(state | props) 的长度是否一致,每一个 key 是否两者都有,并且是否是一个引用,也就是只比较了第一层的值,确实很浅,所以深层的嵌套数据是对比不出来的。

实例

在React Component的生命周期中,有一个shouldComponentUpdate方法。这个方法默认返回值是true。

这意味着就算没有改变组件的props或者state,也会导致组件的重绘。这就经常导致组件因为不相关数据的改变导致重绘,这极大的降低了React的渲染效率。比如下面的例子中,任何options的变化,甚至是其他数据的变化都可能导致所有cell的重绘。


{
this.props.items.map(i =>
<Cell data={i} option={this.props.options[i]} />
)
}

重写shouldComponentUpdate

为了避免这个问题,我们可以在Cell中重写shouldComponentUpdate方法,只在option发生改变时进行重绘。

shouldComponentUpdate(nextProps, nextState) {
if (this.props.option === nextProps.option) {
return false;
} else {
return true;
}
}

这样每个Cell只有在关联option发生变化时进行重绘。

因为上面的情况十分通用,React创建了PureComponent组件创建了默认的shouldComponentUpdate行为。这个默认的shouldComponentUpdate行为会一一比较props和state中所有的属性,只有当其中任意一项发生改变是,才会进行重绘。

需要注意的是,PureComponent使用浅比较判断组件是否需要重绘

因此,下面对数据的修改并不会导致重绘(假设Table也是PureComponent)

  options.push(new Option())
options.splice(0, 1)
options[i].name = "Hello"

这写例子都是在原对象上进行修改,浅比较只是比较指针的异同,会认为不需要进行重绘。

为了避免出现这些问题,推荐使用immutable.js。immutable.js会在每次对原对象进行添加,删除,修改使返回新的对象实例。任何对数据的修改都会导致数据指针的变化。

import immutable from 'immutable';
const { Map, List } = immutable; componentDidMount(){
const map1 = Map({a:1, b: 2, c: 3})
const map2 = map1.set('b',50)
console.log(map1.get("b")) // 2
console.log(map2.get("b")) // 50 const list1 = this.state.list;
const list2 = list1.push(3,4,5)
const list3 = list2.unshift(0)
const list4 = list1.concat(list2,list3)
console.log(list1.size) //2
console.log(list2.size) //5
console.log(list3.size) //6
console.log(list4.size) //13
}

使用immutable的优点

第一点,丰富的语法糖,有了ImmutableJS,代码中就不会再出现如下内容:

//为了在不污染原对象的前提下增加新的KV
var state = Object.assign({}, state, {
key: value
}); //为了在不污染原数组的前提下插入新元素
var state = [
...state.slice(0, index),
insertData,
...state.slice(index + 1)
];

有时候,为了保证reducer在处理 state 的时候不会改变传入的 state,就要写大量的上述代码。但是有了 Immutable.js,你就可以这么写:

var state = state.set('key', value);

var state = state.splice(index, 1, value);

第二点,性能的提升。由于 immutable 内部使用了 Trie 数据结构来存储,只要两个对象的 hashCode 相等,值就是一样的。这样的算法避免了深度遍历比较,性能非常好。这对我们在进行具体渲染过程中的性能优化非常有用。

更深层的使用请参考http://react-china.org/t/react-redux-immutablejs/9948

使用PureComponent的坑

1、Literal Array与Literal Object 数组字面量 对象字面量

{
this.props.items.map(i =>
<Cell data={i} options={this.props.options || []} />
)
}

若options为空,则会使用[]。[]每次会生成新的Array,因此导致Cell每次的props都不一样,导致需要重绘。解决方法如下:

const default = [];
{
this.props.items.map(i =>
<Cell data={i} options={this.props.options || default} />
)
}

2、内联函数

函数也经常作为props传递,由于每次需要为内联函数创建一个新的实例,所以每次function都会指向不同的内存地址。比如:

render() {
<MyInput onChange={e => this.props.update(e.target.value)} />;
}

以及:

update(e) {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update.bind(this)} />;
}

注意第二个例子也会导致创建新的函数实例。为了解决这个问题,需要提前绑定this指针:

constructor(props) {
super(props);
this.update = this.update.bind(this);
}
update(e) {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update} />;
}

或者使用箭头函数来解决

constructor(props) {
super(props);
}
update=(e)=> {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update} />;
}

与 shouldComponentUpdate 共存

如果 PureComponent 里有 shouldComponentUpdate 函数的话,直接使用 shouldComponentUpdate的结果作为是否更新的依据,没有 shouldComponentUpdate 函数的话,才会去判断是不是 PureComponent ,是的话再去做 shallowEqual 浅比较。

// 这个变量用来控制组件是否需要更新
var shouldUpdate = true;
// inst 是组件实例
if (inst.shouldComponentUpdate) {
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
} else {
if (this._compositeType === CompositeType.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) ||
!shallowEqual(inst.state, nextState);
}
}

老版本兼容写法

import React { PureComponent, Component } from 'react';

class Foo extends (PureComponent || Component) {
//...
}

这样在老版本的 React 里也不会挂掉。

PureComponent 真正起作用的,只是在一些纯展示组件上,复杂组件我认为用了反而会更复杂,该更新的时候不更新,容易造成更多bug,源码里shallowEqual 那一关就过不了。

参考:http://www.wulv.site/2017-05-31/react-purecomponent.html

https://www.jianshu.com/p/33cda0dc316a

PureComponent的更多相关文章

  1. react中PureComponent浅对比策略

    PureComponent实现了Component中没有实现的shouComponentUpdata()方法,会对state和props进行一次浅对比,本文介绍一下浅对比策略 源码中,实现浅对比的函数 ...

  2. 从 0 到 1 实现 React 系列 —— 5.PureComponent 实现 && HOC 探幽

    本系列文章在实现一个 cpreact 的同时帮助大家理顺 React 框架的核心内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/PureComponent/HOC/...) ...

  3. React-性能优化pureComponent

    每当store里有数据更新时,render()函数就会执行,有时候store的更新数据与本组件并没有关系,render()不必执行. 我们可以用shouldComponentUpdate来优化组件. ...

  4. 【react】---pureComponent的理解

    一.pureComponent的理解  pureComponent表示一个纯组件,可以用来优化react程序.减少render函数渲染的次数.提高性能 pureComponent进行的是浅比较,也就是 ...

  5. PureComponent的作用及一些使用陷阱

    默认渲染行为的问题 在React Component的生命周期中,有一个shouldComponentUpdate方法.这个方法默认返回值是true. 这意味着就算没有改变组件的props或者stat ...

  6. React 中的 Component、PureComponent、无状态组件 之间的比较

    React 中的 Component.PureComponent.无状态组件之间的比较 table th:first-of-type { width: 150px; } 组件类型 说明 React.c ...

  7. react优化--pureComponent

    shouldComponentUpdate的默认渲染 在React Component的生命周期中,shouldComponentUpdate方法,默认返回true,也就意味着就算没有改变props或 ...

  8. React Native(六)——PureComponent VS Component

    先看两段代码: export class ywg extends PureComponent { …… render() { return ( …… ); } } export class ywg e ...

  9. anu - pureComponent

    import { inherit } from "./util"; import { Component } from "./Component"; impor ...

  10. React性能优化 PureComponent

    为什么使用? React15.3中新加了一个 PureComponent 类,顾名思义, pure 是纯的意思, PureComponent 也就是纯组件,取代其前身 PureRenderMixin  ...

随机推荐

  1. Java企业微信开发_06_素材管理之上传本地临时素材文件至微信服务器

    一.本节要点 1.临时素材有效期 media_id是可复用的,同一个media_id可用于消息的多次发送(3天内有效) 2.上传文件时的http请求里都有啥 具体原理可参看: 为什么上传文件的表单需要 ...

  2. python-管理MySQL之ConfigParser模块

    1.拷贝2.7版本的ConfigParser.py模块支持无值解析 cp /usr/local/src/Python-2.7.5/Lib/ConfigParser.py /usr/lib/python ...

  3. 2_flyweight, 轻量化模式

    ### instanced rendering. send shared data to gpu just once mesh, texture, leaves push every instance ...

  4. leetcode 6 ZigZag Conversion(水题)

    就是简单的模拟一下就可以了.但是我一开始是用一个二维char数组来存的,这样在最终扫全体时会扫很多空的位置,浪费了很多时间,所以就time limit error了. 所以改进一下就用string数组 ...

  5. bison 编译sql的基本知识

    一.bison是干什么的? bison 是一个语法分析器,把用户输入的内容,根绝在.y文件中事先定义好的规则,构建一课语法分析树.(所谓的规则就是,匹配上对应字符之后,执行相应的动作.) 1.一个简单 ...

  6. Struts2 - 配置文件中result 节点详解

    每个 action 方法都将返回一个 String 类型的值, Struts 将根据这个值来决定响应什么结果. 每个 action 声明都必须包含有数量足够多的 result 元素, 每个 resul ...

  7. 重写ScrollView实现两个ScrollView的同步滚动显示

    1.背景介绍 最近项目用到两个ScrollView的同步显示,即拖动左边的ScrollView滚动的同时,实现右边的ScrollView同步滚动.此种情形常用在复杂界面布局中,比如左边的ScrollV ...

  8. freeMarker(九)——程序开发指南补充知识

    学习笔记,选自freeMarker中文文档,译自 Email: ddekany at users.sourceforge.net 1.变量.范围 本章介绍当模板在访问变量时发生了什么事情,还有变量是如 ...

  9. bzoj 1941 [Sdoi2010]Hide and Seek——KDtree

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1941 第二道KDtree! 枚举每个点,求出距离它的最远和最近距离.O( n * logn ...

  10. 二 Flask快速入门

    1: 外部可访问的服务器: 如果你运行了这个服务器,你会发现它只能从你自己的计算机上访问,网络中其它任何的地方都不能访问.在调试模式下,用户可以在你的计算机上执行任意 Python 代码.因此,这个行 ...