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>


        );
    }
}

你可能感兴趣的:(ReactNative,前端)