在React中使用SetInterval卸载组件

时间:2017-03-30 00:26:59

标签: javascript reactjs setinterval unmount

我正在尝试使用setInterval卸载组件。

这是基于答案here

组件:

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

现在,当我转到另一页时,我收到此错误:

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component

所以我添加了这样的东西:

   componentWillUnmount(){
    clearInterval(this.interval);
  }

我也试过了:

   componentWillUnmount(){
    clearInterval(this.changeActiveMedia);
  }

但我仍然每5秒钟收到上述错误。有没有正确的方法来清除间隔?

1 个答案:

答案 0 :(得分:16)

setInterval会返回您可以在clearInterval中使用的时间间隔ID。

More info on setInterval

这样的事情应该有效:

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

然后在componentWillUnmount:

clearInterval(this.myInterval);