【发布时间】:2021-03-03 22:41:44
【问题描述】:
我的代码显示轮播时收到此警告。 警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。
我尝试使用 componentWillUnmount 取消订阅,但警告仍然存在。下面是我的代码。
constructor(props) {
super(props);
const idxStart = 0;
this.state = {
current: idxStart,
prev: this.getPrevIndex(idxStart),
next: this.getNextIndex(idxStart),
Text: Text
};
// To disable autoplay, change to false
this.autoPlay = true;
}
getPrevIndex = (idx) => {
if (idx <= 0) {
return pics.length - 1;
}
return idx - 1;
}
getNextIndex = (idx) => {
if (idx >= pics.length - 1) {
return 0;
}
return idx + 1;
}
setIndexes = (idx, dir) => {
this.setState({
current: idx,
prev: this.getPrevIndex(idx),
next: this.getNextIndex(idx),
dir
});
}
transitionSlide = (direction) => {
if (this.moving) return;
// start animation
this.setState({
dir: direction,
move: true
});
this.moving = true;
//stop animation
setTimeout(() => {
this.setState({
move: false
});
if (direction === 'next') {
this.setIndexes(this.getNextIndex(this.state.current), 'next');
} else {
this.setIndexes(this.getPrevIndex(this.state.current), 'prev');
}
this.moving = false;
}, 500);
}
componentDidMount() {
if (this.autoPlay) {
setInterval(this.handleNext, 6000);
}
}
componentWillUnmount() {
this.autoplay === false
clearInterval(setInterval(this.handleNext, 6000));
clearTimeout(setTimeout(() => {
this.setState({
move: false
});
if (direction === 'next') {
this.setIndexes(this.getNextIndex(this.state.current), 'next');
} else {
this.setIndexes(this.getPrevIndex(this.state.current), 'prev');
}
}, 500))
}
handlePrev = () => {
this.transitionSlide('prev');
}
handleNext = () => {
this.transitionSlide('next');
}```
I have tried to fix this perhaps there is something I am not doing right.
【问题讨论】:
标签: javascript reactjs