任务需求:做一个搜索框,根据用户输入内容不断进行模糊搜索,使搜索结果可以分页,下拉触发更多数据。搜索结果用了一个ListView控件,并使用了onEndReached函数。
如下所示:
<ListView
keyboardShouldPersistTaps='always'
dataSource={ds.cloneWithRows(this.state.dataSource)}
renderRow={this._renderRow.bind(this)}
enableEmptySections={true}
onEndReachedThreshold={100}
onEndReached={()=>this.loadingData()}>
</ListView>
loadingData(){
pageNum++;
if(pageNum>Math.ceil(this.state.total/20)){
return;
}
var jsonData = {
"sessionId": global.appInfo.sessionId,
"merchName": content,
"pageNum":pageNum,
};
console.log(jsonData)
Utils.fetchData(this.props.fetchUrl, jsonData, this.SearchCallback);
}
当ListView和其他子组件在外面加了一个ScrollView时,debugg发现在一直不停地触发onEndReached函数,也就是说父组件ScrollView能滚动,导致ListView中的数据不能满屏,于是就不停地触发该函数,不停fetch请求。
还有,当listView的dataSource第一次渲染时,如果为空,也会触发onEndReached函数,比如我在搜索框输入内容是,因为监听函数的触发,在函数内使用了setState,重新渲染了页面,也是第一次渲染dataSource,于是便会触发onEndReached函数,这样便连续Fetch请求了pageNum=1和pageNum=2
_onChangeText(text) {
pageNum=1;
if (text) {
this.setState({ inputValue: text, dataSource: [], recordingIsVisible: false }) //把这行去掉,便不会触发onEndReached函数
console.log("old id:" + this.settimeId);on
clearTimeout(this.settimeId);
content = text;
this.settimeId = setTimeout(() => {
var jsonData = {
"sessionId": global.appInfo.sessionId,
"merchName": text,
"pageNum":pageNum,
};
Utils.fetchData(this.props.fetchUrl, jsonData, this.SearchCallback);
}, 1000);
console.log("sheng chen id:" + this.settimeId);
} else {
this.setState({ recordingIsVisible: true, inputValue: '' })
}
}
<TextInput underlineColorAndroid="transparent" placeholder={"商户简称/全称"} style={{ marginLeft: 10, width: 150 }}
onChangeText={this._onChangeText.bind(this)}
value={this.state.inputValue}
ref="keyWordInput">
</TextInput>
坑多多,o(╥﹏╥)o
如图模糊搜索