搜索框樣式
<View style={{ paddingRight: 15, paddingLeft: 15, marginTop: 10 }}>
<View style={{ height: 40, backgroundColor: "#fff", borderRadius: 10, paddingLeft: 25, flexDirection: 'row', alignItems: 'center' }} >
<Image source={require('../images/search/magnifier.png')} style={{ width: 15, height: 15 }}></Image>
<TextInput underlineColorAndroid="transparent" placeholder="商戶簡稱/全稱" style={{ marginLeft: 10, width: 150 }}
onChangeText={this._onChangeText.bind(this)}
value={this.state.inputValue}
ref="keyWordInput"
onSubmitEditing={() => { this.refs.keyWordInput.blur() }}>
</TextInput>
<TouchableOpacity onPress={() => { dismissKeyboard() }} style={styles.searchView}>
<Text style={{ color: '#0391ff', fontSize: 14 }}>搜索</Text>
</TouchableOpacity>
</View>
</View>
思路:關於實現實時搜索,在搜索關鍵字的過程中需要不停地向服務器發起請求,這樣才能根據輸入的內容呈現不同的搜索結果。可是如果不停地fetch請求,因爲fetch請求是異步進行,在輸入第一個字的時候開始fetch請求,此時又輸入的二個字,而第一個fetch請求還沒結束,第二個fetch請求又來,這樣會造成服務器崩潰,也不會有良好的用戶體驗。所以在做模糊搜索的時候,要儘量減少服務器請求,儘可能地根據用戶停頓時間一步到位地知道用戶想搜索什麼,從而給出結果。
通過在textInput的監聽函數中進行
onChangeText={this._onChangeText.bind(this)}
_onChangeText(text) {
if (text) {
this.setState({ inputValue: text }) //實時變化值
clearTimeout(this.settimeId); //如搜索的內容變化在1秒之中,可以清除變化前的fetch請求,繼而減少fetch請求。但不能中斷fetch請求
this.settimeId = setTimeout(() => {
var jsonData = {
"sessionId": global.appInfo.sessionId,
"merchName": text,
};
console.log(jsonData)
Utils.fetchData('nsposm/B1404/queryMerchList', jsonData, this.SearchCallback);
}, 1000); //讓每次要進行fetch請求時先延遲1秒在進行
console.log("sheng chen id:" + this.settimeId);
} else {
this.setState({inputValue: '' })
}
}