2016-12-13 46 views
4

我正在研究React Redux應用程序,我對某種最佳實踐有相當基本的疑問。React Redux - 通過道具或連接將數據傳遞到組件

我已經MainComponent(一種容器),在那裏我取數據上componentDidMount:

class MainComponent extends React.Component { 
    componentDidMount(){ 
    this.fetchData() 
    } 
    fetchData() { 
    this.props.fetchDataAction() 
    } 
    render() { 
    return (
     <div> 
     <ChildComponent1 /> 
     <ChildComponent2 /> 
     </div> 
    ) 
    } 
} 
export default connect(mapStateToProps,{fetchDataAction})(MainComponent) 

如何獲取的數據傳遞給ChildComponents?最佳做法是什麼?兩種可能的解決方案是(恕我直言 - 或許更多?)

解決方案一:

class MainComponent extends React.Component { 
... 
render() { 
    return (
    <div> 
     <ChildComponent1 dataOne={this.props.data.one} /> 
     <ChildComponent2 dataTwo={this.props.data.two} /> 
    </div> 
) 
} 
... 

二的解決方案 - 連接ChildComponents到存儲由fetchDataAction()在MainComponent更新:

class ChildComponent1 extends React.Component { 
    render() { 
    return (
     <div> 
     {this.props.one} 
     </div> 
    ) 
    } 
} 
function mapStateToProps(state){ 
    return (
    one: state.one 
) 
} 
export default connect(mapStateToProps,null)(ChildComponent1) 

現在當ChildComponents不執行更新存儲和第二個解決方案時,我使用第一種解決方案。但我不確定這是否合適。

+0

看看我的[回覆](http://stackoverflow.com/questions/41043122/redux-provider-not-passing-down-props-state/41043535#41043535) –

+0

謝謝。 React.cloneElement - 我不知道。但問題是,哪種方法是最佳做法還是取決於某些條件 – magnat

+0

您好@magnat您給出的示例最適合遵循智能和啞元組件結構。注意:MainComponent負責獲取數據,因此我們將其設置爲容器(智能)並將其與redux存儲庫連接起來。子組件(愚蠢)只是採取單獨的數據/回調作爲道具父母和渲染它們。通過這種方式,您不會失敗容器和組件的用途,通過反應更新組件並保持組件可重用,防止額外的計算。留下我的評論在這裏,也許這對未來有幫助。 –

回答

0

如果您有多個子組件,並且您必須將一部分獲取的數據傳遞給不同的子組件;我會建議保持父組件作爲單一來源。

你可以嘗試這樣的: -

class MainComponent extends React.Component { 

    constructor(){ 
    super() 
    this.state = { 
     data : {} 
    } 
    } 

    componentDidMount(){ 
    this.fetchData() 
    } 
    fetchData() { 
    this.props.fetchDataAction() 
    } 

    componentWillReceiveProps(nextProps){ 
    //once your data is fetched your nextProps would be updated 
    if(nextProps.data != this.props.data && nextProps.data.length>0){ 
     //sets your state with you data--> render is called again 
     this.setState({data:nextProps.data}) 
    } 
    render() { 
    //return null if not data 
    if(this.state.data.length === 0){ 
     return null 
    } 
    return (
     // it should have keys as one and two in api response 
     <div> 
     <ChildComponent1 data={data.one}/> 
     <ChildComponent2 data={data.two}/> 
     </div> 
    ) 
    } 
} 

function mapStateToProps(state){ 
    return (
    data: state 
) 
} 
export default connect(mapStateToProps,{fetchDataAction})(MainComponent) 

我覺得所有的邏輯停留在這樣一個地方。假如你打算在未來添加更多的子組件,你只需要在上面添加一行代碼並在API中進行少許更改。但是,如果您閱讀每個組件,則已連接該組件以再次存儲,這使其更加複雜。

所以如果除了獲得data之外,如果您的子組件中沒有任何其他邏輯,我會將此邏輯保留在父組件中。

相關問題