2017-02-13 12 views
0

次の2つの同等のパフォーマンスが賢明ですか?最初の例ではMyComponentの小道具が更新されるたびにComponent1Component2が再レンダリングされますか?props/stateを使用してrender()にコンポーネントを表示するかどうかを選択すると、毎回再描画されますか?

import React from 'react'; 
import { connect } from 'react-redux'; 
import { createStructuredSelector } from 'reselect'; 
import { selectShowComponent1, selectShowComponent2 } from './selectors'; 

@connect(createStructuredSelector({ 
    showComponent1: selectShowComponent1, 
    showComponent2: selectShowComponent2, 
})) 
class MyComponent extends React.PureComponent { 
    static propTypes = { 
    showComponent1: React.PropTypes.bool, 
    showComponent2: React.PropTypes.bool, 
    }; 

    render() { 
    const { showComponent1, showComponent2 } = this.props; 
    return (
     <div> 
     {showComponent1 ? (<Component1>shown 1</Component1>) : ''} 
     {showComponent2 ? (<Component2>shown 2</Component2>) : ''} 
     </div> 
    ); 
    } 
} 

export default MyComponent; 
import React from 'react'; 
import { connect } from 'react-redux'; 
import { createStructuredSelector } from 'reselect'; 
import { selectShowComponent1, selectShowComponent2 } from './selectors'; 

@connect(createStructuredSelector({ 
    showComponent1: selectShowComponent1, 
    showComponent2: selectShowComponent2, 
})) 
class MyComponent extends React.PureComponent { 
    static propTypes = { 
    showComponent1: React.PropTypes.bool, 
    showComponent2: React.PropTypes.bool, 
    }; 

    render() { 
    const { showComponent1, showComponent2 } = this.props; 
    return (
     <div> 
     <Component1 renderMe={showComponent1}>shown 1</Component1> 
     <Component2 renderMe={showComponent2}>shown 2</Component2> 
     </div> 
    ); 
    } 
} 

export default MyComponent; 
+0

第2のアプローチは、両方のコンポーネントをレンダリングし、それらのコンポーネントの内側で表示するものを管理します。一方、最初のアプローチは、あなたの小道具で何かが変わるたびに新しいコンポーネントをマウントします。 – Kejt

答えて

1

最初のものは、第1のに対しず、毎回再レンダリングされます。理由は、動的に生成されたコンポーネントです(この場合は、3項演算子の結果であるため、動的です)、動的コンテキストから返されるたびに新しいキーが与えられます。そして、この鍵は、Reactが内部的にコンポーネントを識別するために使用するものです。あなたがそれらを明示的にキーを与えた場合

は、だから私は信じている:

それらを再レンダリングされて停止する必要があり、理論的には次に
{showComponent1 ? (<Component1 key="1">shown 1</Component1>) : ''} 
    {showComponent2 ? (<Component2 key="2">shown 2</Component2>) : ''} 

が、それはいくつかのシナリオでは理想的なように手動で割り当てるキーコンポーネントを意味するかもしれませんがないかもしれませんあなたが実際にそれをしたいときに再レンダリングします。

+0

ありがとうございます。キーは、各コンポーネント内で「スコープ」されていますか?複数のコンポーネントで同じキーを使用すると競合が発生する可能性がありますか?つまり、ヘッダーコンポーネントにリストがあり、項目のキーが1,2,3 ...の場合、同じキー値が割り当てられた項目を含むフッターの別のリストが競合しますか? – dimvic

+0

それらは、兄弟関係(つまり、親の下のレベル)に関して一意である必要があります。 – Jayce444

関連する問題