【React】- 使用节流

今日在工作中遇到项目卡顿,导致按钮多次点击后多次提交的问题,于是想着为按钮加个节流,但是在使用时发现和在js中使用不太一样,摸索出来其使用方法,这里简单记录下,等后续有时间再去深入了解其原理。

1.使用自己写的节流函数

import React, { useState } from "react";
import { Button } from "antd";
export default function index() {
  const [pre, setPre] = useState(0);

  // 节流函数
  const throttle =
    (fn, delay) =>
    (...rest) => {
      const current = Date.now();
      if (current - pre > delay) {
        fn(rest);
        setPre(current);
      }
    };

  // 对按钮点击事件包装一层节流
  const click_handle = () => {
    throttle(click, 2000)();
  };

  // 点击事件真正的逻辑写这里
  const click = () => {
    console.log("点击");
  };
  return (
    <div>
      <Button onClick={click_handle}>点击</Button>
    </div>
  );
}

2.使用lodash库中的方法throttle

在函数组件中使用

import React from "react";
import { Button } from "antd";
import throttle from "lodash/throttle"; //引入lodash中的节流函数
export default function index() {
  // 对按钮点击事件包装一层节流
  const click_handle = throttle(() => click(), 2000);
  // 点击事件真正的逻辑写这里
  const click = () => {
    console.log("点击");
  };
  return (
    <div>
      <Button onClick={click_handle}>点击</Button>
    </div>
  );
}

在类组件中使用

import React, { Component } from "react";
import throttle from "lodash/throttle";
import { Button } from "antd";
export default class index extends Component {
  // 对按钮点击事件包装一层节流
  click_handle = throttle(() => this.click(), 2000);

  // 点击事件真正的逻辑写这里
  click = () => {
    console.log("点击");
  };
  render() {
    return (
      <div>
        <Button onClick={this.click_handle}>点击</Button>
      </div>
    );
  }
}

在类组件中还有一种使用方式

import React, { Component } from "react";
import throttle from "lodash/throttle";
import { Button } from "antd";
export default class index extends Component {
  constructor(props) {
    super(props);
    this.click_handle = throttle(this.click_handle, 2000);
  }
  // 点击事件真正的逻辑写这里
  click_handle = () => {
    console.log("点击");
  };
  render() {
    return (
      <div>
        <Button onClick={this.click_handle}>点击</Button>
      </div>
    );
  }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值