React组件机能优化:PureRender和Immutable Data

1 媒介

网页机能最大的限定要素是阅读重视绘(reflow)和重排版(repaint),React的假造DOM就是为了尽量削减阅读器的重绘和重排版,从React的衬着历程看,防止不必要的衬着能够进一步进步机能。

2 PureRender

React优化要领中最罕见的就是PureRender,PureRender的道理是从新完成shouldComponentUpdate生命周期要领,让当前传入的state和props和之前的做浅比较,假如返回FALSE,组件就不实行render要领,默许状况返回TRUE。react-addons-pure-render-mixin插件许可我们在ES6 的classes语法中运用PureRender:

        import React,{component} from ‘react’;
        import PureRenderMixin from ‘react-addons-pure-render-mixin’;
        
        class App extends Component{
            constructor(props){
                super(props);
                //!!!
                this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
            }
        render(){
            return <div calssName = {this.props.className}>foo</div>;
            }
        }

3 Immutable Data

在通报数据时,能够经由过程Immutable Data进一步提拔组件的衬着机能,Immutable Data是针对可变对象和不可变对象所做的折中。可变对象是指多个变量援用一个对象,这致使对象的time和value耦合,对象一旦转变没法重塑;不可变对象是指每次用到一个对象就举行深复制,这致使内存糟蹋;Immutable Data完成的道理基于耐久化数据构造,也就是运用旧数据建立新数据时,旧数据照旧保留,而且为了防止深度复制,Immutable Data运用构造同享,也就是说,假如对象树中的一个节点变化,只修正这个节点和受他影响的父节点,其他节点照旧同享。Immutable Data长处体现在降低了可变数据带来的时候和值的耦合;节省了内存,能够完成数据的时候游览,也就是说数据能够重塑。

运用Immutable Data能够直接采纳Facebook开辟的immutable.js库,该库具有完美API,而且和原生JavaScript对象对应。Immutable Data能够和PureRender连系运用,前面提到,PureRender经由过程浅比较肯定shouldComponentUpdate的返回值,然则浅比较能够掩盖的场景不多,深比较本钱高贵。而Immutable.js供应了高效推断数据是不是转变的要领,只需要全等算符(===)和自带的is()要领就能够晓得是不是实行render要领,这个操纵几乎是零本钱的,所以能够极大地进步机能。运用immutable data以后,仅仅转变状况了的组件及其父组件被从新衬着。

        import React,{ commponent } from 'react';
        import { is } from 'immutable';
        
        class App extends Component {
            shouldComponentUpdate(nextProps, nextState){
                const thisProps = this.props || {};
                const thisStae = this.state || {};
                if (Object.keys(thisProps).length !== Object.keys(nextProps).length ||
                    Object.keys(thisState).length !== Object.keys(nextState).length){
                    return true;
                }
                for (const keys in nextProps){
                   // !==推断原生对象,is推断immutable对象
                    if (thisProps[key] !== nextProps[key] ||
                            !is(thisProps[key], nextProps[key]))
                        return true;
                }
                for (const key in nextState){
                    if ( thisStae[key] !== nextState[key])||
                        !is(thisStae[key],nextState[key])
                    return true;
                }
            }
        }

题目:Immutable Data能够和PureRender连系运用是简朴的作用叠加吗?优先级哪一个更高呢?这类作用叠加有无机能消耗呢?我当前的明白是,react-addons-pure-render-mixin插件引的PureRender有缺点,由于浅复制有时会致使比较失误,immutable.js仅仅是弥补了这一题目,反而增加了代码量,那为何不痛快将PureRender去掉,只用immutable.js呢?

    原文作者:zhangding
    原文地址: https://segmentfault.com/a/1190000008533923
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞