componentDidMount() invokes immediately after a component mounts. You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.
Although you have a console log statement in your componentDidMount function it may not be executing because that function never gets run. If the error occurs before componentDidMount gets called such as in your render function, you won't see the console log.
According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function. It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.
The example below shows a classical approach to access componentDidMount(). import React, { Component } from 'react'; class App extends Component { componentDidMount() { // Runs after the first render() lifecycle console. log("Did mount called"); } render() { console.
Learning ReactJS I am working on a simple countdown app. The Countdown component looks like this:
const Countdown = React.createClass({
getInitialState: function() {
return {
remaining: 10,
running: true,
};
},
componentDidMount: function(){
if (this.state.running) {
setInterval(this.tick, 1000);
} else {
console.log("already paused");
};
},
tick: function(){
if (this.state.remaining === 0) {
this.setState({ remaining: 10 });
this.props.updateStats();
} else {
this.setState({ remaining: this.state.remaining -1 });
};
},
handlePauseClick: function(){
this.setState({ running: false });
},
render: function(){
const s = this.state.remaining;
return (
<div className='ui centered card'>
<div className='content centered'>
<h1>{helpers.secondsToHuman(s)}</h1>
<ButtonControls
handlePauseClick={this.handlePauseClick}
/>
</div>
</div>
)
},
});
The countdown starts running. When clicking on the pause button it is supposed to stop. The componentDidMount only runs the timer when running is true:
if (this.state.running) {
setInterval(this.tick, 1000);
} else {
console.log("already paused");
};
After handling the click with:
this.setState({ running: false });
I was expecting that the component gets re-rendered and that componentDidMount will be executed again. This is not happening though. componentDidMount seems only to run once.
Thanks for your ideas
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With