Tuesday, May 22, 2018

javascript - setTimeout() in componentDidMount() does not work




I am trying to change the state of a component every 5 seconds as below inside componentDidMount() hook



import React, { Component } from 'react';

export default class ToTest extends Component {


constructor(props) {
super(props);
this.state = {
test: false
};
}

componentDidMount() {
setTimeout(() => { this.setState({ test: !this.state.test }) }, 5000);
}


renderDiv() {
if(this.state.test) {
return (
test is true
)
}
else {
return (
test is false
)
}
}
render() {

return (
{ this.renderDiv() }

);
}
}


But it executes only once. It changes from false to true once and then nothing.
What am I missing?


Answer




componentDidMount() is only executed once when the component mounts and you only schedule it once. You have to use setInterval() to schedule it periodically.



Also when you update the state based on the current state you should use a callback in setState() that takes the previous state as react may batch multiple calls to setState().



And don't forget to cancel the timer in componentWillUnmount():



import React, { Component } from 'react';

export default class ToTest extends Component {
state = {

test: false,
};

componentDidMount() {
this.timer = setInterval(
() => this.setState(prevState => ({ test: !prevState.test })),
5000,
);
}


componentWillUnmount() {
clearInterval(this.timer);
}

// other methods ...
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...