在 React 中使用 SetInterval 卸载组件
Unmounting a Component with a SetInterval in React
我正在尝试使用 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>
)
}
}
现在,当我转到另一个页面时,出现此错误:
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
returns 您可以在 clearInterval
.
中使用的间隔 ID
像这样的东西应该可以工作:
this.myInterval = setInterval(this.changeActiveMedia.bind(this), 5000)
然后在 componentWillUnmount:
clearInterval(this.myInterval);
我正在尝试使用 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>
)
}
}
现在,当我转到另一个页面时,出现此错误:
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
returns 您可以在 clearInterval
.
像这样的东西应该可以工作:
this.myInterval = setInterval(this.changeActiveMedia.bind(this), 5000)
然后在 componentWillUnmount:
clearInterval(this.myInterval);