reactjs - ComponentDidMount vs ComponentWillMount? -
i have question regarding when componentdidmount , when fires, i'm new working react, , examples documentation vague. why 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 asking why eventmap
not contain li
string 'componentwillmount has been called'
. because cannot push
items this.state
. have call this.setstate
cause render
function run again.
also, it's not clear why you're returning object key mount
, componentwillmount
not pass result anything.
componentwillmount: function() { var events = this.state.events; events.push('a new value') this.setstate({ events: events }); // important! }
you're wonder why in componentdidmount
function console message not appear. because cannot have new line after return:
componentdidmount: function() { return // magic semi-colon gets added here, nothing below happen. console.log('mounted!'); }
do right thing , put stuff you're returning on same line (or use parens)
componentdidmount: function() { return console.log('mounted!'); },
or
componentdidmount: function() { return ( console.log('mounted!'); ) }
but, rather rude @zerkms has pointed out, makes no sense return function.. points out why console.log not firing.
i find these docs component lifecycle pretty clear, keep them open:
Comments
Post a Comment