2017-02-22 56 views
2

我有一個容器組件,它將一組對象傳遞給一個表示組件輸出。反應:將簡單的邏輯放在Container或Presentational組件中?

在演示組件中,我需要顯示符合特定條件的這些對象的數量。最好的做法是在容器組件中執行計數並將其傳遞給演示組件,或者可以在演示組件中進行計數。

即:

export class ResultsPage extends React.Component { 

    constructor(props){ 
    super(props); 
    } 

    countSexyObjects(){ 
    const matching = this.props.allObjects.filter((obj)=>{ 
     return obj.sexy === true; 
    }); 

    return matching.length 
    } 

    render(){ 
    return (
     <PresentationalComponent allObjects={this.props.allObjects} 
            numberOfSexyObjects={this.countSexyObjects()} /> 
    ); 
    } 
} 


let PresentationalComponent = (props) => { 

    return (
    <div> 
     There are {props.numberOfSexyObjects} sexy objects 
    </div> 
); 
}; 

OR

export class ResultsPage extends React.Component { 

    constructor(props){ 
    super(props); 
    } 

    render(){ 
    return (
     <PresentationalComponent allObjects={this.props.allObjects} /> 
    ); 
    } 
} 


let PresentationalComponent = (props) => { 

    const countSexyObjects =() => { 
    const matching = this.props.allObjects.filter((obj)=>{ 
      return obj.sexy === true; 
     }); 

    return matching.length 
    }; 

    return (
    <div> 
     There are {countSexyObjects()} sexy objects 
    </div> 
); 
}; 

回答

1

理想狀態被認爲是反應的邪惡。我知道React建立在狀態概念的基礎上,但更少的狀態是更受歡迎的,這意味着嘗試使用大多數本質上純粹的函數來構建代碼。

恕我直言在你的第一個例子是更正確的。 ResultsPage是你的容器組件(智能組件),而另一個是愚蠢的。啞組件不管理狀態,只是照顧用戶界面的外觀。你可以把所有的html,bootstrap邏輯放在那裏。

之所以出現這種模式是很好的,因爲現在,讓我們說,你想從一個XHR調用獲取的匹配標準,你在第二種情況下的代碼將

export class ResultsPage extends React.Component { 

    constructor(props){ 
    super(props); 
    } 

    getSexyMatcher() { 
    /* make ajax call here */ 
    return results; 
    } 

    render(){ 
    return (
     <PresentationalComponent allObjects={this.props.allObjects} sexyMatcher={getSexyMatcher()}/> 
    ); 
    } 
} 


let PresentationalComponent = (props) => { 

    const countSexyObjects =() => { 
    const matching = this.props.allObjects.filter((obj)=>{ 
      return obj.sexy.match(props.sexyMatcher) 
      // return obj.sexy === true; 
     }); 

    return matching.length 
    }; 

    return (
    <div> 
     There are {countSexyObjects()} sexy objects 
    </div> 
); 
}; 

注意到你怎麼了修改兩處相同業務邏輯的組件?更糟的是,如果別人在代碼庫的其他地方使用了PresentationalComponent呢? 在第一種情況下,事情要簡單得多。只需在智能組件中添加ajax函數並將結果傳遞給UI組件。

+1

此鏈接可能會有所幫助 - https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.2vdpxfulp – kaushik94

1

我會用第一格式的幾個原因:

  • 智能組件應該有更好的瞭解什麼是「 SexyObject「是。如果它在對象中是一個領域,那很簡單,可以用任何方式來論證。如果它依賴於Web服務或一些更復雜的邏輯來確定它是否性感,那麼在表示層中就不會需要它。簡單有一種轉向複雜的方式,所以我會使用最初支持複雜性的結構。

  • 隨着智能組件中的邏輯測試代碼將變得更加簡單。您可以灌注組件,然後檢查固定數據集中的輸出變量。

  • 如果組件的「SexyObject」條件可以更改,那麼如果保持選擇邏輯分離,則可以保留重用您的表示組件的功能。

只是我的$ 0.02