Re-render react component when its props changes

I am using React and Redux in a project and
I’ve two components a parent and a child.

The parent component passes some props to the child when the child component receives those props it calls some action which change some of the props (async) that the parent passed to its child. Now my redux-store shows that the data has successfully stored in it. But my child component doesn’t re-render itself.

Parent Component:

 class Parent extends React.Component {
  getChilds(){
    let child = [];
    let i = 0;
    for (let keys in this.props.home.data) {
      child[i] = (
        <Child title={keys} data={this.props.home.data[keys]} key={keys} />
      );
      i++;
      if (i === 6) break;
    }

    return Rows;
  }
  render(){
return (
  <div>
     <h1>I am gonna call my child </h1>
    {this.getChilds()}
 </div>)
  }
}

Child Component:

class Child extends React.Component {
 // Here I'm not sure which lifecycle method to use to i'm gonna use
// componentDidMount
 componentDidMount(){
  if(this.props.data.items.length === 0){
    // calling an action to fill this.props.data.items array with data
   this.props.getData(this.props.data.id);
  }
 }
  getGrandSong(){
  let grandSons = [];
  if(this.props.data.items.length > 0){
   grandSons = this.props.data.items.map( item => <GrandSon item={item} />);
  }
  return grandSons;
 }
  render(){
    return (
      <div>
       <h1> I am the child component and I will call my own child </h1>
      {this.getGrandSon()}
    </div>
     )
 }
}

Hey,

A couple of points:

  • It shouldn’t be the responsibility if Child to fill in the data. It should receive the data already ready from the parent.
  • About not re-rendering, I could not find anything thing in your code that would cause that, props are automatically updated. Did you try using the React Developer tools extension to debug?

I’ve found the solution
It’s because How React compare props
I think React perform a shallow comparison so it is not re-rendering even though the obj is changing.
So, Now I’m getting the data separately from the obj instead of just one obj.
like this

const mapStateToProps = state => {
  return { 
    id: state.data.id,
   items: state.data.items
}
}

instead of

 const mapStateToProps = state => {
  return {
   data: state.data
}
}
1 Like