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

时间:2015-06-20 03:19:20

标签: javascript state react-native

对于上下文,我正在处理这个React Native Tutorial

这个日志让我困惑的方式。当我通过键入" a"更改空输入字段时,控制台输出如下。那么" b"。

PropertyFinder

Console log

这是我的SearchPage类。为什么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>
    );
}
}

1 个答案:

答案 0 :(得分:4)

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