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秒ごとに上記のエラーがまだ発生しています。間隔をクリアする適切な方法はありますか?