
image.png
提供了兩個函數(shù)
debounce和throttle具體的可以看這篇文章
一:debounce去抖:使用場景
例如:一個搜索框,輸入1,請求數(shù)據(jù)得到包含1的數(shù)據(jù);再輸入2,得到包含12的數(shù)據(jù)...假如用戶想得到1234的數(shù)據(jù),就要調(diào)用4次接口得到,浪費請求資源,本地數(shù)據(jù)渲染也會走多次。 debounce可以解決此問題
/*
this.getData 請求方法
500 延遲時間
option 配置
lodash在opitons參數(shù)中定義了一些選項,主要是以下三個:
leading,函數(shù)在每個等待時延的開始被調(diào)用,默認值為false
trailing,函數(shù)在每個等待時延的結(jié)束被調(diào)用,默認值是true
maxwait,最大的等待時間,因為如果debounce的函數(shù)調(diào)用時間不滿足條件,可能永遠都無法觸發(fā),
因此增加這個配置,保證大于一段時間后一定能執(zhí)行一次函數(shù)
*/
this.handleClickDebounce = _.debounce(this.getData, 500, { 'maxWait': 1000 });
使用
import * as _ from 'lodash'
export default class App extends Component<Props> {
constructor(props){
super(props);
this.state = {
text: ''
}
this.textChange = this.textChange.bind(this);
this.getData = this.getData.bind(this);
this.handleClickDebounce = _.debounce(this.getData, 500, { 'maxWait': 1000 });
}
componentWillUnmount() {
this.handleClickDebounce.cancel();
}
textChange(text){
console.log('text==',text)
this.setState({
text
});
this.handleClickDebounce()
}
getData(){
console.log('模擬請求接口: 請求數(shù)據(jù)中...')
}
render() {
return (
<View style={styles.container}>
<Text style={{marginTop: 44}}>函數(shù)去抖:用與防止輸入框頻繁搜索</Text>
<TextInput style={{height: 44, backgroundColor: 'red', }}
value={this.state.text}
onChangeText={(text)=>{this.textChange(text)}}
/>
</View>
);
}
}

QQ20190213-114115.gif

image.png
二:throttle節(jié)流:使用場景
例如:一個按鈕,點擊要調(diào)用接口,接口成功跳轉(zhuǎn)到下一個頁面。這是頻繁的點擊,頻繁的調(diào)用接口,會導致頁面跳轉(zhuǎn)多次。throttle可以解決此問題
/*
* this.onPress 需要調(diào)用的方法
* 1000 1秒之內(nèi)不讓重復(fù)調(diào)用
*
*option 配置
lodash在opitons參數(shù)中定義了一些選項,主要是以下三個:
leading,函數(shù)在每個等待時延的開始被調(diào)用,默認值為false
trailing,函數(shù)在每個等待時延的結(jié)束被調(diào)用,默認值是true
maxwait,最大的等待時間,因為如果debounce的函數(shù)調(diào)用時間不滿足條件,可能永遠都無法觸發(fā)
因此增加這個配置,保證大于一段時間后一定能執(zhí)行一次函數(shù)
*
* */
this.handleClickThrottled = _.throttle(this.onPress, 1000);
使用
import * as _ from 'lodash'
export default class App extends Component<Props> {
constructor(props){
super(props);
this.handleClickThrottled = _.throttle(this.onPress, 1000);
}
componentWillUnmount() {
this.handleClickThrottled.cancel();
}
onPress() {
console.log('1秒調(diào)用一次該方法')
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handleClickThrottled} style={{height: 100, marginTop: 200, backgroundColor: 'red'}}>
<Text>函數(shù)節(jié)流:用于防重復(fù)點擊</Text>
</TouchableOpacity>
);
}
}

QQ20190213-114710.gif