2015-06-20 39 views
3

对于情况下,我对这个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> 
    ); 
} 
} 

回答

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

+0

谢谢科林。这绝对有帮助。我主要来自Objective-C背景下的React Native开发。所以JavaScript和React的世界是相当新的。你会推荐任何网站学习JavaScript /反应超越文档? –

+1

我的主要建议是学习JavaScript的基础知识,然后在其上放置React。为此目的:http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript –