Unmounting a Component with a SetInterval in React

泄露秘密 提交于 2019-12-12 08:41:55

问题


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);



来源:https://stackoverflow.com/questions/43106443/unmounting-a-component-with-a-setinterval-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!