react如何卸载组件_在React中使用SetInterval卸载组件

react如何卸载组件_在React中使用SetInterval卸载组件我正在尝试使用setInterval卸载组件。这是基于这里的答案:零件:classImageSliderextendsReact.Component{constructor(props){super(props);this.state={activeMediaIndex:0};}componentDidMount(){setInterval(this.changeActive…

我正在尝试使用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(

react如何卸载组件_在React中使用SetInterval卸载组件

);

}

render(){

return(

{this.renderSlideshow()}

)

}

}

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

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秒就会收到上述错误。有清除间隔的适当方法吗?

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/36759.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注