2016-08-03 62 views
0

我的一些組件僅連接到auth簡化器,因爲他們需要知道用戶是否經過身份驗證/登錄的唯一原因。 我創建了一個更高階的組件(withAuth)來包裝這些組件(並添加isLogged prop),但我不知道它是否是一個好的模式。可以在同一HoC中包裝類似連接的組件,而不是將它們全部連接()以相同的方式連接到auth reducer?

ps - 所描述的用例被簡化了,還有一些更多的屬性/動作被映射。

感謝您的幫助!

編輯 - 這裏是一些代碼來說明:讓我們假設,我們有一些小部件共享的代碼(添加一些映射動作,道具等)

import React, { PropTypes } from 'react' 
import { connect } from 'react-redux' 
import { getIsLogged } from 'authManager/reducer' 

const Widget1 = props => { 
    return <div>{props.isLogged ? 'yay!' : 'nope'}</div> 
} 

Widget1.propTypes = { 
    isLogged: PropTypes.bool.isRequired 
} 

const mapStateToProps = (state) => { 
    return { 
    isLogged: getIsLogged(state) 
    } 
} 

export default connect(
    mapStateToProps 
)(Widget1) 

我只是重構創建以下HOC

import React, { PropTypes } from 'react' 
import { connect } from 'react-redux' 
import { getIsLogged, getFirstName } from 'authManager/reducer' 

const withAuth = ComposedComponent => { 
    class _hoc extends React.Component { 
    render() { 
     return <ComposedComponent {...this.props} /> 
    } 
    } 

    _hoc.propTypes = { 
    isLogged: PropTypes.bool.isRequired, 
    firstName: PropTypes.string 
    } 

    const mapStateToProps = (state, {params}) => { 
    return { 
     isLogged: getIsLogged(state), 
     firstName: getFirstName(state) 
    } 
    } 

    return connect(
    mapStateToProps 
)(_hoc) 
} 

export default withAuth 

現在所有的以前的部件是這樣的:

import React, { PropTypes } from 'react' 
import withAuth from 'hoc/withAuth' 

const Widget1 = props => { 
    return <div>{props.isLogged ? 'yay!' : 'nope'}</div> 
} 

Widget1.propTypes = { 
    isLogged: PropTypes.bool.isRequired 
} 

export default withAuth(Widget1) 

I ST藝術想知道是否有什麼東西我做錯了連接的組件/容器,以及那個HoC應該是(或是?)。

無論如何,問題是:這是一個好的舉措嗎?

+0

你有一些代碼來說明嗎?一般來說,在HOCs中包裝組件是一種方法。 – Lee

+0

@李,這裏是代碼! – vgrafe

+0

對我來說很好! – Lee

回答

2

你的代碼完全沒問題。連接組件的慣用方法是將那些最「接近」的組件連接到他們需要的數據上。 創建HoC withAuth絕對是一個不錯的選擇。您不必擔心應用程序中連接組件的數量太多,因爲pub/sub模式的複雜度爲O(n),連接組件的數量爲O(n)。因爲你不可能有成千上萬的人,所以處理連接到商店的許多HoC並不是什麼大不了的事情。

+0

謝謝你的答案!你認爲一個組件被包裝成'withAuth' connected/smart/container,或者presentational/dumb? – vgrafe

+0

我提到的'withAuth'組件是上面提到的那個,所以它是一個連接/智能/容器。 – Pcriulan

相關問題