react-native 节流和防抖函数

debounce去抖:使用场景

例如:一个搜索框,输入1,请求数据得到包含1的数据;再输入2,得到包含12的数据…假如用户想得到1234的数据,就要调用4次接口得到,浪费请求资源,本地数据渲染也会走多次。 debounce可以解决此问题

/*
this.getData 请求方法
500 延迟时间
option 配置
lodash在opitons参数中定义了一些选项,主要是以下三个:
   leading,函数在每个等待时延的开始被调用,默认值为false
   trailing,函数在每个等待时延的结束被调用,默认值是true
   maxwait,最大的等待时间,因为如果debounce的函数调用时间不满足条件,可能永远都无法触发,
            因此增加这个配置,保证大于一段时间后一定能执行一次函数
*/
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('模拟请求接口: 请求数据中...')
    }

    render() {
        return (
            <View style={styles.container}>
                <Text style={{marginTop: 44}}>函数去抖:用与防止输入框频繁搜索</Text>
                <TextInput style={{height: 44, backgroundColor: 'red', }}
                           value={this.state.text}
                           onChangeText={(text)=>{this.textChange(text)}}
                />
            </View>
        );
    }
}

throttle节流:使用场景

例如:一个按钮,点击要调用接口,接口成功跳转到下一个页面。这是频繁的点击,频繁的调用接口,会导致页面跳转多次。throttle可以解决此问题

/*
* this.onPress 需要调用的方法
* 1000 1秒之内不让重复调用
*
*option 配置


lodash在opitons参数中定义了一些选项,主要是以下三个:
   leading,函数在每个等待时延的开始被调用,默认值为false
   trailing,函数在每个等待时延的结束被调用,默认值是true
   maxwait,最大的等待时间,因为如果debounce的函数调用时间不满足条件,可能永远都无法触发
            因此增加这个配置,保证大于一段时间后一定能执行一次函数
*
* */


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秒调用一次该方法')
    }
    render() {
        return (
            <View style={styles.container}>


                <TouchableOpacity onPress={this.handleClickThrottled} style={{height: 100, marginTop: 200, backgroundColor: 'red'}}>
                    <Text>函数节流:用于防重复点击</Text>
                </TouchableOpacity>


        );
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值