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".

propertyfinder

console log

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.

https://facebook.github.io/react/docs/component-api.html


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -