当前位置:网站首页>11.自定义hooks
11.自定义hooks
2022-06-30 09:32:00 【山川pro】
- 只在组件初始化时执行的 Hook。
import {
useEffect } from 'react';
import {
isFunction } from '@src/utils/type';
export default function useMount(func) {
if (process.env.NODE_ENV === 'development') {
if (!isFunction(func)) {
console.error(`useMount: parameter \`fn\` expected to be a function, but got "${
typeof func}".`);
}
}
useEffect(() => {
func?.();
}, []);
}
- 返回当前最新值的 Hook,可以避免闭包问题。
import {
useRef } from 'react';
function useLatest(value) {
const ref = useRef(value);
ref.current = value;
return ref;
}
export default useLatest;
- 节流hook
import {
throttle } from 'lodash';
import {
useMemo } from 'react';
import {
isFunction } from '@src/utils/type';
import useLatest from '../useLatest';
import useUnmount from '../useUnMount';
function useThrottleFn(fn, options) {
if (process.env.NODE_ENV === 'development') {
if (!isFunction(fn)) {
console.error(`useThrottleFn expected parameter is a function, got ${
typeof fn}`);
}
}
const fnRef = useLatest(fn);
const wait = options?.wait ?? 1000;
const debounced = useMemo(
() =>
throttle(
(...args) => {
fnRef.current(...args);
},
wait,
options,
),
[],
);
useUnmount(() => {
debounced.cancel();
});
return {
run: debounced,
cancel: debounced.cancel,
flush: debounced.flush,
};
}
export default useThrottleFn;
- 防抖hook
import {
debounce } from 'lodash';
import {
useMemo } from 'react';
import {
isFunction } from '@src/utils';
import useLatest from '../useLatest';
import useUnmount from '../useUnMount';
/** * @description: 用来处理防抖的hook * @param {Function} fn: 需要防抖执行的函数 * @param {Object} options: 配置防抖的行为 * wait: 等待时间 * maxWait: 最大等待时间 * @return {Object} * run: 触发执行 fn,函数参数将会传递给 fn * cancel: 取消防抖 * flush: 立即调用当前防抖函数 */
function useDebounceFn(fn, options) {
if (process.env.NODE_ENV === 'development') {
if (!isFunction(fn)) {
console.error(`useDebounceFn expected parameter is a function, got ${
typeof fn}`);
}
}
const fnRef = useLatest(fn);
const wait = options?.wait ?? 1000;
const debounced = useMemo(
() =>
debounce(
(...args) => {
fnRef.current(...args);
},
wait,
options,
),
[],
);
useUnmount(() => {
debounced.cancel();
});
return {
run: debounced,
cancel: debounced.cancel,
flush: debounced.flush,
};
}
export default useDebounceFn;
- 可以对effect依赖数组进行深层比较的hook
import {
useEffect, useRef } from 'react';
import {
isEqual } from 'lodash';
const depsEqual = (aDeps, bDeps) => isEqual(aDeps, bDeps);
function createDeepCompareEffect(hook) {
return (effect, deps) => {
const ref = useRef();
const signalRef = useRef(0);
if (deps === undefined || !depsEqual(deps, ref.current)) {
ref.current = deps;
signalRef.current += 1;
}
hook(effect, [signalRef.current]);
};
}
export default createDeepCompareEffect(useEffect);
边栏推荐
- 4. use ibinder interface flexibly for short-range communication
- Talking about kotlin process exception handling mechanism
- The elegant combination of walle and Jianbao
- 八大排序(二)
- DataTableToModelList实体类
- Talk about how the kotlin collaboration process establishes structured concurrency
- Experience of an acmer
- 12. problem set: process, thread and JNI architecture
- Tclistener server and tcpclient client use -- socket listening server and socketclient use
- 8.8 heap insertion and deletion
猜你喜欢

八大排序(二)

ES6 learning path (III) deconstruction assignment

Set, map and modularity

Couldn't load this key (openssh ssh-2 private key (old PEM format))

Duplicate entry '2' for key 'primary appears in JPA‘

JVM tuning tool commands (notes)

Flutter 0001, environment configuration

Framework program of browser self-service terminal based on IE kernel

Express の Hello World

Wechat development tool (applet)
随机推荐
Talk about the kotlin cooperation process and the difference between job and supervisorjob
RPC understanding
The elegant combination of walle and Jianbao
float
Framework program of browser self-service terminal based on IE kernel
Set, map and modularity
Microsoft. Bcl. Async usage summary -- in Net framework 4.5 project Net framework version 4.5 and above can use async/await asynchronous feature in C 5
Why must redis exist in distributed systems?
MySQL internal component structure
银河麒麟server-V10配置镜像源
What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?
Deep understanding of kotlin collaboration context coroutinecontext
Talking about the difference between kotlin collaboration and thread
Solution to pychart's failure in importing torch package
How do I start? (continuously updating)
What are the SQL add / delete / modify queries?
Recommend a very easy-to-use network communication framework HP socket
JPA naming rules
Small program learning path 1 - getting to know small programs
[wechat applet] realize applet pull-down refresh and pull-up loading