在react中使用防抖以及节流函数

在react中使用防抖以及节流函数

这里已防抖函数举例;

debounce.js
export const debounce=(fn, wait=1000)=> {
  var timer = null;

  return function () {
      var context = this
      var args = arguments
      if (timer) {
          clearTimeout(timer);
          timer = null;
      }
      timer = setTimeout(function () {
          fn.apply(context, args)
      }, wait)
  }
}


export const throttle  = (fn, gapTime=500)=> {
  let _lastTime = null;
  
  return function () {
    let _nowTime = + new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn();
      _lastTime = _nowTime
    }
  }
}

在react组件中使用

index.jsx

import React from 'react';
import {debounce} from '@utils/debounce'
class Demo extends React.component{
	add=(item)=>{
		console.log(item)//想要传的参数'
	}
	fn=debounce(this.add)
	render (){
		return 
} }
class Test extends Component {
  constructor(props) {
    super(props);
    this.state={
      test:'我是子组件的返回值'
    }
  }

  add = debounce((t)=>{
    console.log('t',t)//t 123123123

      return this.state
  })
  render() {
    return (
      
); } }

你可能感兴趣的:(其他,react,react,防抖,react节流)