Respond to a State Change with Unexpected Registration
In context, I am working on this React Native Tutorial
The way these magazines confuse me. Below is the console output when I changed the empty input field by typing "a" then "b".
Here is my SearchPage class. Why console.log('searchString = ' + this.state.searchString);
shows the previous value for 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 for houses to Buy!
</Text>
<Text style = {styles.description}>
Search by place name or search near your 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>
);
}
}
source to share
setState
can be asynchronous rather than synchronous. This means that state updates can be clumped together and not performed immediately to improve performance. If you really need to do something after the state has actually been updated, there is a callback parameter:
this.setState({ searchString: event.nativeEvent.text }, function(newState) {
console.log('Changed State');
console.log('searchString = ' + this.state.searchString);
}.bind(this));
More information setState
can be found in the documentation.
source to share