I have a question regarding when componentDidMount and when it fires, I'm new to working with react, and the examples for the documentation are vague. why is my component not firing?
var App = React.createClass({
getInitialState: function() {
var events = ['initial state has been called'];
return {
events: events
}
},
componentWillMount: function() {
return {
mount: this.state.events.push('componentWillMount has been called')
}
},
componentDidMount: function() {
return
console.log('mounted!');
},
render: function() {
var eventMap = this.state.events.map(function(event, i) {
return <li key={i}>{event}</li>;
})
return (
<div>
<ul>
{eventMap}
</ul>
</div>
)
}
})
ReactDOM.render(
<App />,
document.getElementById('container')
)
You might be asking why your eventMap does not contain the li with the string 'componentWillMount has been called'. This is because you cannot push items to this.state. You have to call this.setState which will cause your render function to run again.
Also, it's not clear why you're returning an object with the key mount, as componentWillMount does not pass its result to anything.
componentWillMount: function() {
var events = this.state.events;
events.push('a new value')
this.setState({ events: events }); // important!
}
You're probably also wonder why in your componentDidMount function the console message does not appear. This is because you cannot have a new line after return:
componentDidMount: function() {
return // magic semi-colon gets added here, nothing below will happen.
console.log('mounted!');
}
Do the right thing and put stuff you're returning on the same line (or use parens)
componentDidMount: function() {
return console.log('mounted!');
},
OR
componentDidMount: function() {
return (
console.log('mounted!');
)
}
But, as the rather rude @zerkms has pointed out, it makes no sense to return anything from this function.. this simply points out why your console.log was not firing.
I find these docs about component lifecycle to be pretty clear, so keep them open:
https://facebook.github.io/react/docs/component-specs.html
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