React Redux - transfer data to components through props or connect

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.

+4
1

, ; .

- : -

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, .

0

Source: https://habr.com/ru/post/1663606/


All Articles