使用意外日志记录响应本机更改状态

React Native Change State With Unexpected Logging

对于上下文,我正在研究这个React Native Tutorial

这个日志的方式让我很困惑。以下是我通过键入 "a" 然后 "b" 更改空输入字段时的控制台输出。

这是我的搜索页面 class。为什么 console.log('searchString = ' + this.state.searchString); 显示 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可以是异步操作,不是同步的。这意味着状态更新可以一起批处理,而不是立即完成,以获得性能提升。如果你真的需要在状态真正更新后做一些事情,有一个回调参数:

this.setState({ searchString: event.nativeEvent.text }, function(newState) {
    console.log('Changed State');
    console.log('searchString = ' + this.state.searchString);
}.bind(this));

您可以在文档中阅读有关 setState 的更多信息。

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