Reputation: 805
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.
Upvotes: 0
Views: 772
Reputation: 2106
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
Upvotes: 0
Reputation: 882
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
Upvotes: 2
Reputation: 1598
you can try with in your child component
shouldComponentUpdate(nextProps, nextState) {
if(nextProps.gaitStats != this.props.gaitStatus) {
this.forceUpdate();
}
}
Upvotes: 0