javascript - React Native Change State With Unexpected Logging -
for context, working on react native tutorial
the way logs confuses me. following console output when changed empty input field typing "a" "b".
here's searchpage class. why console.log('searchstring = ' + this.state.searchstring);
show previous value this.state.searchstring
?
class searchpage extends component { constructor(props) { super(props); this.state = { searchstring: 'london' }; } onsearchtextchanged(event) { console.log('onsearchtextchanged'); console.log('searchstring = ' + this.state.searchstring + '; input text = ' + event.nativeevent.text ); this.setstate({ searchstring: event.nativeevent.text }); console.log('changed state'); console.log('searchstring = ' + this.state.searchstring); } render () { console.log('searchpage.render'); return ( <view style={styles.container}> <text style = { styles.description }> search houses buy! </text> <text style = {styles.description}> search place name or search near location. </text> <view style={styles.flowright}> <textinput style = {styles.searchinput} value={this.state.searchstring} onchange={this.onsearchtextchanged.bind(this)} placeholder='search via name or postcode'/> <touchablehighlight style ={styles.button} underlaycolor = '#99d9f4'> <text style ={styles.buttontext}>go</text> </touchablehighlight> </view> <touchablehighlight style={styles.button} underlaycolor= '#99d9f4'> <text style={styles.buttontext}>location</text> </touchablehighlight> <image source={require('image!house')} style={styles.image}/> </view> ); } }
setstate
can asynchronous operation, not synchronous. means updates state batched , not done in order performance boost. if really need after state has been updated, there's callback parameter:
this.setstate({ searchstring: event.nativeevent.text }, function(newstate) { console.log('changed state'); console.log('searchstring = ' + this.state.searchstring); }.bind(this));
you can read more on setstate
in documentation.
Comments
Post a Comment