简体   繁体   中英

Child component is not updating when parent state changes

I have a parent component with an array in its state, the array is added too over time.

This is the parent. There is a lot going on in it but I've distilled it down to the main concerns the state, componentShouldUpdate function (which works for everything else the component needs to do) and the show data method which also works (I can confirm that gaitStats does update properly).

  class GaitMeasure extends Component {
  constructor(props) {
    super(props);

    this.state = {
      grabData: null;
      gaitStats: []
    };
  }  
  shouldComponentUpdate(nextProps) {
   if (this.props.data !== null) {
     if (this.props.data !== nextProps.data) {
       this.showData();
    }
      return false;
    }
   if (this.props.canvas.x !== null) {
     return true;
   } 
  if (this.state.grabData) {
    return true;
  }

  return false;
}

showData() {
....

const avgGait = [...this.state.gaitStats];

avgGait.push(Math.abs(rightX - leftX));

this.setState({
  timeline: this.state.timeline + 3,
  gaitStats: avgGait
});

// render

GaitStat, child:

class GaitStat extends Component {
  constructor(props) {
    super(props);
  }


  render() {
    return (
      <div>
        Hi
        <p>{this.props.gaitStats}</p>
      </div>
    );
  }
}

From what I can tell GaitStat doesn't ever rerender this.state.gaitStatus as a prop after the initial render. The prop remains an empty array regardless of how many times the parent rerenders or updates it's state.

Your shouldComponentUpdate method prevents the class from updating when it's state changes. You should update you shouldComponentUpdate method to the folowing

shouldComponentUpdate(nextProps, nextState) {
   if(nextState !== this.state){
        return true;
   }
   if (this.props.data !== null) {
     if (this.props.data !== nextProps.data) {
       this.showData();
    }
      return false;
    }
   if (this.props.canvas.x !== null) {
     return true;
   } 
   if (this.state.grabData) {
     return true;
   }

  return false;
}

You can find more information about shouldComponentUpdate here

you can try with in your child component

shouldComponentUpdate(nextProps, nextState) { 
  if(nextProps.gaitStats != this.props.gaitStatus) {
   this.forceUpdate();
 }
}

try this:

 shouldComponentUpdate(nextProps) {
   if ((this.props.data === null && this.props.data !== nextProps.data) || this.props.canvas.x !== null || this.state.grabData) {
        return true;
      }
  this.showData();
  return false;
}

this includes all your condition to render in one if and if noting meet the criteria then run showData and return false eg don't update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM