Unmounting a Component with a SetInterval in React

2019-04-07 20:34发布

问题:

I'm trying to unmount a component with a 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'm still getting the above error every 5 seconds. Is there a proper way to clear the interval?

回答1:

setInterval returns an in interval Id that you can use in clearInterval.

More info on setInterval

Something like this should work:

this.myInterval = setInterval(this.changeActiveMedia.bind(this), 5000)

then in componentWillUnmount:

clearInterval(this.myInterval);