2016-12-13 43 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之外,如果您的子组件中没有任何其他逻辑,我会将此逻辑保留在父组件中。

相关问题