自定义hooks

8 篇文章 0 订阅
3 篇文章 0 订阅

记录一下自己封装的hooks

1.一个请求数据的hook,利用useState和useEffect来获取数据,最后将获取到的数据返回出去。

import { useState, useEffect } from 'react'
import api from '@/api'

// 获取领导指标明细
function useGetLeaderDetailData(props) {
  const { dt, orgType, chartType } = props
  const [headerBossData, setHeaderBossData] = useState([])
  useEffect(() => {
    const params = {
      dt,
      orgType,
      chartType,
      orgCode: '00072218',
      appCode: 'lhm-supply-chain-operate'
    }
    if (dt) {
      api
        .getLeaderDetail(params)
        .then((ret) => {
          setHeaderBossData(ret)
        })
        .catch((e) => {
          console.log(e)
        })
    }
  }, [dt, orgType, chartType])

  return headerBossData
}

export default useGetLeaderDetailData

2.封装一个节流函数的hook

import { useState, useEffect } from 'react';

function useThrottle(value, delay) {
  const [throttledValue, setThrottledValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setThrottledValue(value);
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);

  return throttledValue;
}

// 使用方式

function MyComponent() {
  const [count, setCount] = useState(0);

  const throttledCount = useThrottle(count, 1000); // 每秒最多执行一次

  function handleIncrement() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {throttledCount}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

上述代码中,useThrottle 函数接受两个参数:

  • value:需要节流的值
  • delay:节流的时间间隔,单位是毫秒

该函数返回一个经过节流处理的值 throttledValue。每当 value 发生变化时,会启动一个定时器,在 delay 时间后将 value 更新到 throttledValue 中。

在组件中,我们可以使用 useThrottle 将需要节流处理的值传入,然后使用返回的 throttledValue。在上述示例中,我们使用按钮来增加一个计数器的值,每次点击后会将 count 的值加 1,但是这个值经过 useThrottle 处理,每秒最多只会更新一次,从而实现了节流的效果。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值