[英]How to clear a settimeout in react
On each question component, I am trying to clear the time out.在每个问题组件上,我都试图清除超时。 So on componentWillMount()
I will start the timer and then on componentDidUpdate()
I will clear the timeout.因此,在componentWillMount()
上我将启动计时器,然后在componentDidUpdate()
上我将清除超时。 The timer does not seem to be working.After the timer expires I will push the user back to the home page.计时器似乎不起作用。计时器到期后,我会将用户推回主页。 Any idea why the using clearTimeout()
isnt working?知道为什么使用clearTimeout()
不起作用吗?
class Questions extends Component {
constructor(props){
super(props);
this.state ={
error: false,
position: null,
redirect: false
}
this.error = this.error.bind(this);
this.errorFalse = this.errorFalse.bind(this);
this.timer = this.timer.bind(this);
}
timer=()=>{
setTimeout(() => {
console.log('this ran')
this.setState({
redirect: true
})
}, 5000)
}
componentWillMount(){
this.setState({
error: false
})
this.timer();
}
componentDidUpdate(prevProps, prevState, snapshot, timer){
console.log('updated')
clearTimeout(this.timer);
}
When you use setTimeout()
it returns a timeoutID
, which you use to clear the timeout.当您使用setTimeout()
它会返回一个timeoutID
,您可以使用它来清除超时。
To use it in your component, you need to store the timeoutID
that was returned from the timer
method:要在您的组件中使用它,您需要存储从timer
方法返回的timeoutID
:
class Questions extends Component {
constructor(props) {
super(props)
this.state = {
error: false,
position: null,
redirect: false
}
this.error = this.error.bind(this);
this.errorFalse = this.errorFalse.bind(this);
// this.timer = this.timer.bind(this); // don't bind an arrow function
}
timer = () => setTimeout(() => { // return the timeoutID
console.log('this ran')
this.setState({
redirect: true
})
}, 5000);
componentWillMount() {
this.setState({
error: false
})
this.timeoutID = this.timer(); // cache the timeoutID
}
componentDidUpdate(prevProps, prevState, snapshot, timer) {
console.log('updated')
clearTimeout(this.timeoutID); // clear the timeoutID
}
React Hooks反应钩子
useEffect(() => {
const timer = () => setTimeout(() => ...some work ... , 2000);
const timerId = timer();
return () => {
clearTimeout(timerId);
};
});
The best way in React to clear Timeouts and Intervals are by assinging ref to your interval/timeout functions which works flawlessly and use useRef() hook React 中清除超时和间隔的最佳方法是将 ref 分配给您的间隔/超时函数,该函数可以完美运行并使用 useRef() 钩子
clearTimerRef = useRef();
clearIntervalRef = useRef();
clearTimerRef.current = setTimeout(timerFunction, 5000);
clearIntervalRef.current = setInterval(intervalFunction, 5000);
const stopFunction = () => {
clearInterval(clearIntervalRef.current)
clearTimeout(clearTimerRef.current)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.