记录一下自己封装的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
处理,每秒最多只会更新一次,从而实现了节流的效果。