2017-04-04 152 views
0

我有一些React組件需要獲取某些項目才能顯示。這些組件可以是功能組件,除非有一個非常簡單的componentDidMount回調。有沒有一個好的設計模式可以讓我返回到功能組件?React設計模式獲取項目

class Things extends React.Component { 

    componentDidMount() { 
    this.props.fetchThings() 
    } 

    render() { 
    things = this.props.things 
    ... 
    } 
} 

我使用的反應,終極版,我也用connect到我的組件連接到我的減速器和行動。這裏是該文件:

import { connect } from 'react-redux' 
import Things from './things' 
import { fetchThings } from '../../actions/thing_actions' 

const mapStateToProps = ({ things }) => ({ 
    things: things, 
}) 

const mapDispatchToProps =() => ({ 
    fetchThings:() => fetchThings() 
}) 

export default connect(mapStateToProps, mapDispatchToProps)(Things) 

取而代之的是在這個文件中的東西是否有意義?也許是這樣的:

import { connect } from 'react-redux' 
import Things from './things' 
import { fetchThings } from '../../actions/thing_actions' 

const mapStateToProps = ({ things }) => ({ 
    things: things, 
}) 

class ThingsContainer extends React.Component { 
    componentDidMount() { 
    fetchThings() 
    } 
    render() { 
    return (
     <Things things={this.props.things} /> 
    ) 
    } 
} 

export default connect(mapStateToProps)(ThingsContainer) 

回答

1

功能部件意味着是組件不什麼。你只是給他們道具,他們渲染。事實上,如果你的組件需要獲取任何東西,那麼很可能你的組件應該被轉換成一個獲取你需要的數據的container。然後,您可以將組件的UI部分抽象爲一個或多個純粹的功能組件,通過傳遞作爲道具獲取的數據來呈現您的容器。

我相信表示/容器組件拆分是您在這裏尋找的模式。

+0

感謝您的回覆。我知道容器的設計模式,但它看起來像是過度殺傷,因爲'fetchThings'實際上是該組件唯一的功能。 但這給了我一個想法。如果我使用「'connect」文件,我已經必須讓組件道具也可以獲取這些東西?我用這個想法編輯了我的問題。 –

+1

這會使你的組件呈現和連接,當涉及到較大的組件時,這通常會被忽略,但對於小型組件來說可以。 –

+0

真的嗎?爲什麼會皺起眉頭?我通常會看到redux的優勢,它可以讓你使用更多的功能組件,通過使用連接來爲你的reducer直接提供道具。 –