我想在我的React Component中创建一个setTimeout,但是setTimeout每秒渲染2次。我不明白为什么(:
我的组件代码:
componentDidMount() {
this._isMounted = true;
if (this._isMounted) {
this.clearTimeout();
}
}
componentWillUnmount () {
this.clearTimeout();
}
clearTimeout = () => {
window.clearTimeout(this.timeout);
this.setState({ timer: 0 });
}
runCounter() {
const { timer, duration, max_duration } = this.state;
const offset = 5;
const startDuration = offset;
const endDuration = parseInt(duration) + offset;
let startMaxDuration;
let endMaxDuration;
if (!max_duration) {
startMaxDuration = (this.props.store.get('session').maxdurationDefault *60) - 10 + offset;
endMaxDuration = startMaxDuration + 10;
} else {
startMaxDuration = max_duration - 10 + offset;
endMaxDuration = startMaxDuration + 10;
}
this.timeout = window.setTimeout(() => {
this.setState({ timer: timer + 1 });
console.log(this.state.timer); // 2 times re-render
switch (this.state.timer) {
case startDuration:
this.startDuration();
break;
case endDuration:
this.endDuration();
break;
case startMaxDuration:
this.startMaxDuration();
break;
case endMaxDuration:
this.endMaxDuration();
return false;
break;
}
this.runCounter();
}, 1000);
}
render() {
<div>
{showStartCounter &&
<Counter begin={5} end={0} className="is-absolute" />
}
{showQuestionCounter &&
<Counter begin={0} end={duration} maxDuration={max_duration} className="is-offset" />
}
{showQuestionMaxDuration &&
<Counter begin={10} end={0} maxDuration={max_duration} className="is-absolute" />
}
</div>
}
我在点击事件上运行runCounter
方法。
任何人都知道为什么我的setTimeout每秒重新渲染2次?我不明白问题出在哪里:)
谢谢社区!