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