javascript - 在 React 中使用 SetInterval 卸载组件

标签 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 秒收到一次上述错误。有没有正确的方法来清除间隔?

最佳答案

setInterval 返回一个可以在 clearInterval 中使用的间隔 ID。

More info on setInterval

像这样的东西应该可以工作:

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

然后在componentWillUnmount:

clearInterval(this.myInterval);

关于javascript - 在 React 中使用 SetInterval 卸载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106443/

相关文章:

javascript - 如何在 AJAX 调用中查询应用程序状态?

android - 无法连接远程调试器

Angular clearinterval不停止间隔

带有多个选项卡弹出警报的 Javascript session 超时

javascript - 在选项卡完全关闭时保持 setInterval 运行

javascript - VM299 :1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON. 解析(<匿名>)

javascript - 如何功能检测输入事件级别 1 或 2 支持?

javascript - 映射 JSON 对象 - ReactJS

javascript - 跳过解析 javascript 时定期返回的 2 行

javascript - 为什么最后一个元素被称为 "remove"