我在react中有一个简单的滑块,除一个功能(Thumbnails)外,其他所有功能均正常。该功能停止滑块,将单击的图像设置为活动滑块,然后再次启动滑块。滑块的setInterval设置为3秒,但是单击的幻灯片在6s之后消失,然后一切恢复正常,而下一张幻灯片在3s之后消失。我确定setState中的createdImages可能会导致此错误,如果删除此错误,一切都会恢复正常。让我知道您是否需要所有代码。
startSlider(){
this.setState(previousState => {
return {
slide: previousState.slide +1,
createdImages: this.state.imagesArray.map((image, index) => {
return (
<img
alt={'photos'}
key={image}
className={index === this.state.slide ? "active" : ""}
src={require(`./img/${image}.png`)}
/>
);
})
};
});
if(this.state.slide === this.state.imagesArray.length){
this.setState({
slide:0
});
}
}
componentDidMount() {
this.sliderInterval = setInterval(this.startSlider, 3000);
}
componentWillUnmount() {
clearInterval(this.sliderInterval);
}
thumbnails(e){
clearInterval(this.sliderInterval);
document.getElementsByClassName('active')[0].setAttribute("class", "");
let imgIndex = parseInt(e.target.id, 10)
this.setState({
createdImages: this.state.imagesArray.map((image, index) => { /// !!! Probably this cause error
return (
<img
alt={'photos'}
key={image}
className={index === imgIndex ? "active" : ""}
src={require(`./img/${image}.png`)}
/>
);
}),
slide: imgIndex
});
this.sliderInterval = setInterval(this.startSlider, 3000); // !!! Everything after ' , ' multiped by 2x, but only one time
}