使用意外日志记录来响应本机更改状态 [英] React Native Change State With Unexpected Logging
问题描述
对于上下文,我正在研究 React Native教程
For context, I am working on this React Native Tutorial
这种记录方式使我感到困惑.以下是当我通过键入"a"然后"b"更改空输入字段时的控制台输出.
The way this logs confuses me. The following is the console output when I changed an empty input field by typing "a" then "b".
这是我的SearchPage类.为什么console.log('searchString = ' + this.state.searchString);
显示this.state.searchString
的先前值?
Here's my SearchPage class. Why does console.log('searchString = ' + this.state.searchString);
show 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>
);
}
}
推荐答案
setState
可以是异步操作,而不是同步操作.这意味着可以将状态更新汇总在一起,而不是立即进行更新以提高性能.如果您真的真正地更新了状态后确实需要做一些事情,则可以使用一个回调参数:
setState
can be an asynchronous operation, not synchronous. This means that updates to state could be batched together and not done immediately in order to get a performance boost. If you really need to do something after state has been truly updated, there's a callback parameter:
this.setState({ searchString: event.nativeEvent.text }, function(newState) {
console.log('Changed State');
console.log('searchString = ' + this.state.searchString);
}.bind(this));
您可以在文档中的setState
上阅读更多内容.
You can read more on setState
in the documentation.
https://facebook.github.io/react/docs/component- api.html
这篇关于使用意外日志记录来响应本机更改状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!