React+Immutable.js的心路歷程

  這段時間作的項目開發中用的是React+Redux+ImmutableJs+Es6開發,總結了immutable.js的相關使用姿式:html

  Immutable Data 顧名思義是指一旦被創造後,就不能夠被改變的數據。能夠經過使用Immutable Data,能夠讓咱們更容易的去處理緩存、回退、數據變化檢測等問題,簡化咱們的開發。react

  咱們知道 react.js很著名的就是它處理dom的作法,它是經過Virtual Dom來查看diff,而後再改動須要改動的Dom。可是有個問題當state更新時,若是數據沒變,react也會去作Virtual Dom的diff,這就產生了浪費,其實這種狀況其實很常見。緩存

  固然React 作性能優化時還有一個避免重複渲染的大招,就是使用生命週期 shouldComponentUpdate(),但它默認返回 true,即始終會執行 render() 方法,而後作 Virtual Dom 比較,並得出是否須要作真實 Dom 更新。性能優化

  這個時候其實還有方案來解決這個問題,用PureRenderMixin,貌似也能夠解決這個問題,在某些狀況下進行性能加速。dom

import PureRenderMixin from 'react-addons-pure-render-mixin';

class FooComponent extends React.Component {

    constructor(props) {

        super(props);

        this.shouldComponentUpdate =PureRenderMixin.shouldComponentUpdate.bind(this);

}

render() {
    return <div className={this.props.className}>foo</div>;
    }
}

  

  其實就是, 實現了 shouldComponentUpdate, 它對當前及下一步的 props 和 state 進行比較,並當相等時返回 false,不進行渲染性能

  看了下PureRenderMixin官方文檔,This only shallowly compares the objects,Only mix into components which have simple props and state。優化

PureRenderMixin,它只是簡單的淺比較,不適用於複雜的比較。this

  順着剛剛的這條思路走,咱們能夠在shouldComponentUpdate()內作判斷,若是有props/state有變化,那麼再進行render(),這個時候的問題就來了,你如何作比較,shallowly compare,達不到效果,deep compare則性能不好spa

  這個時候immutable.js來了,使用immutable.js能夠解決這個問題。component

  首先Immutable.js的拷貝,是當對象樹中一個節點發生變化,只修改這個節點和受它影響的父節點,其它節點則進行共享。

import Immutable from 'immutable';

const initialState = Immutable.fromJS({ data: null });

  

  固然能夠用deep-copy作到這一點,可是差異在於性能。每次deep-copy都要把整個對象遞歸的複製一份。而Immutable的實現像鏈表,添加一個新結點把舊結點的父子關係轉移到新結點上。

生成immutable對象後,而後再在生命週期shouldComponentUpdate作作判斷

shouldComponentUpdate(nextProps) {

    return !this.props.situation.equals(nextProps.situation);

}

  對當前及下一步的 props 的immutable對象 進行比較,並當相等時返回 false,不進行渲染,只有爲true的時候,才進行render()處理。

  react+immutable這樣就能夠大大提高react的性能。

相關文章
相關標籤/搜索