A React Component that iterates over something on each navigation step
If you want to show next image of an array on each click to another page.
- You designed a component that renders on path change: Your component receives path as a prop.
- You show an image of an array according to state counter.
- You let your component change state counter on rendering. Yes, the next rendering should show the next image, shouldn't it?
- And oops, this is an infinite loop. A state change causes a re-rendering.
This helps:
Update state not in rendering but in lifecycle method 'componentDidUpdate'.
componentDidUpdate(prevProps){
// Typical usage (don't forget to compare props):
if (this.props.path!==prevProps.path) {
let count = this.state.count;
this.setState({
count: (count+1) % heroImagesFinalSelectionNumber,
});
}
}
Happy reacting!
Katja