Disabling a component using SetInterval in action
I am trying to unmount a component using setInterval.
This is based on the answer here :
component:
class ImageSlider extends React.Component {
constructor(props) {
super(props);
this.state = { activeMediaIndex: 0 };
}
componentDidMount() {
setInterval(this.changeActiveMedia.bind(this), 5000);
}
changeActiveMedia() {
const mediaListLength = this.props.mediaList.length;
let nextMediaIndex = this.state.activeMediaIndex + 1;
if(nextMediaIndex >= mediaListLength) {
nextMediaIndex = 0;
}
this.setState({ activeMediaIndex:nextMediaIndex });
}
renderSlideshow(){
const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
return(
<div>
<img src={singlePhoto.url} />
</div>
);
}
render(){
return(
<div>
{this.renderSlideshow()}
</div>
)
}
}
Right now when I go to another page I get this error:
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component
So, I added something like this:
componentWillUnmount(){
clearInterval(this.interval);
}
I've also tried:
componentWillUnmount(){
clearInterval(this.changeActiveMedia);
}
But I still get the above error every 5 seconds. Is there a way to clear the interval?
+3
source to share