2016-12-09 23 views
6

我一直在使用react.js創建一個小應用程序。我過分考慮「表現」。如何讓道具不可變以防止在React中重投?

所以我有一個簡單的子組件名爲「微調」。我的目標是確保這個組件不會重新渲染。

這裏是我的組件:

import React, {PureComponent} from 'react'; 

export default class Spinner extends PureComponent { 

render() { 
    return (
     <div className="spinner"> 
      <div className="bounce1"></div> 
      <div className="bounce2"></div> 
      <div className="bounce3"></div> 
     </div> 
    ) 
} 

} 

在重新渲染與時間「反應 - 插件-PERF」,組分總是渲染,我使用PureComponent因爲我想的是組件呈現只有一次,我讀到我可以使用不可改變的道具,但我不知道如何讓這成爲可能。

如果我做一些像這樣:

componentDidMount() { 
    this.renderState = false; 
} 

shouldComponentUpdate(nextProps, nextState) { 
    return (this.renderState === undefined) ? true : this.renderState; 
} 

它渲染只有一次,但我相信有一個更好的辦法。

如何避免重新渲染?或者也許我怎麼能製作一個不可改變的道具?

回答

7

對於componentShouldUpdate,您不需要額外的邏輯,因爲您不希望組件重新渲染。

只添加這應該足以防止組件重新呈現:

shouldComponentUpdate(nextProps, nextState) { 
    return false 
} 
3

對於不需要的道具,我們可以使用一個Functional(無國籍)成分的組合,和巴貝爾的React constant elements transformer無國籍組件優化組件創建,並防止完全重新渲染。

  1. React constant elements transformer添加到您的構建系統。按照docs變壓器會:

    葫蘆元素創建頂端水平是完全 靜子樹,從而降低呼叫React.createElement所得 分配。更重要的是,它告訴React該子樹沒有更改,因此React在協調時可以完全跳過它。

  2. 將微調器更改爲無狀態組件。

    const Spinner =() => (
        <div className="spinner"> 
        <div className="bounce1"></div> 
        <div className="bounce2"></div> 
        <div className="bounce3"></div> 
        </div> 
    ); 
    
    export default Spinner; 
    
+0

現在看起來更好 – FurkanO

0

你可以讓你的道具不可變的陣營,通過使用Immutable JS您陣列的道具變身爲Lists和對象的道具詮釋Maps。有了這個庫,你可以使用簡單的檢查,以檢查數組/對象的相等(而不是通過平等鍵/值會):

shouldComponentUpdate(nextProps) => { 
    this.props.complexObjectAsMap === nextProps.complexObjectAsMap 
} 

但你的組件沒有任何道具 - 這不看看正確的問題。在你的情況下,我會用Ori Drori答案。

相關問題