在React中使用SetInterval卸载组件

los*_*193 7 javascript setinterval unmount reactjs

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

这是基于这里的答案:

零件:

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

   componentWillUnmount(){
    clearInterval(this.interval);
  }
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

   componentWillUnmount(){
    clearInterval(this.changeActiveMedia);
  }
Run Code Online (Sandbox Code Playgroud)

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

小智 17

setInterval返回您可以使用的间隔ID clearInterval.

有关setInterval的更多信息

这样的事情应该有效:

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

然后在componentWillUnmount中:

clearInterval(this.myInterval);