I am working on a React Redux application, and I have a rather fundamental question about some best practices.
I have a MainComponent (container view) where I retrieve data on 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)
How to transfer the received data to ChildComponents? What is the best practice? There are two possible solutions (IMHO - maybe more?)
First decision:
class MainComponent extends React.Component {
...
render() {
return (
<div>
<ChildComponent1 dataOne={this.props.data.one} />
<ChildComponent2 dataTwo={this.props.data.two} />
</div>
)
}
...
The second solution is to include ChildComponents for storage, which is updated by fetchDataAction () in 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)
Now I use the first solution when ChildComponents do not start actions that update the repository and the second solution when they do it. But I'm not sure if this is the right approach.