打開 SearchPage.js,在初始化狀態過程中增加一個message屬性:
~~~
this.state = {
searchString: 'london',
isLoading: false,
message: ''
};
~~~
在render方法中,在UI元素的最后加入:
~~~
<Text style={styles.description}>{this.state.message}</Text>
~~~
這個Text用于向用戶顯示一些文本。
在 SearchPage 類中,在 _executeQuery()方法最后加入:
~~~
fetch(query)
.then(response => response.json())
.then(json => this._handleResponse(json.response))
.catch(error =>
this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
~~~
fetch 函數在?[Fetch API](https://fetch.spec.whatwg.org/)中定義,這個新的JavaScript規范被Firefox 39(Nightly版)以及Chrome 42(開發版)支持,它在XMLHttpRequest的基礎上進行了極大的改進。結果是異步返回的,同時使用了?[promise](http://www.html5rocks.com/en/tutorials/es6/promises/)規范,如果response中包含有效的JSON對象則將JSON對象的response成員(另一個JSON)傳到_handleResponse方法(后面實現)。
然后在 SearchPage類中增加方法:
~~~
_handleResponse(response) {
this.setState({ isLoading: false , message: '' });
if (response.application_response_code.substr(0, 1) === '1') {
console.log('Properties found: ' + response.listings.length);
} else {
this.setState({ message: 'Location not recognized; please try again.'});
}
}
~~~
如果查詢結果成功返回,我們重置 isLoading 屬性為false,然后打印結果集的總行數。
> 注意: Nestoria 有 不以1開頭的響應碼, 這些代碼都非常有用。例如202 和 200表示返回一個推薦位置的列表。當完成這個實例后,你可以嘗試處理這些返回碼,并將列表提供給用戶選擇。
保存,返回模擬器,按下Cmd+R ,然后搜索 ‘london’你將在控制臺看到一條消息,表示搜索到20條房子信息。嘗試輸入一個不存在的地名,比如 ‘narnia’ 你將看到如下信息:

接下來我們在倫敦或者別的什么城市搜索20座房子。