打开 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中定义,这个新的JavaScript规范被Firefox 39(Nightly版)以及Chrome 42(开发版)支持,它在XMLHttpRequest的基础上进行了极大的改进。结果是异步返回的,同时使用了 promise规范,如果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座房子。