当前位置:网站首页>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);
边栏推荐
- 7. know JNI and NDK
- Review the old and know the new
- JVM family
- How do I start? (continuously updating)
- Research on lg1403 divisor
- Golang magic code
- Deep Learning with Pytorch-Train A Classifier
- Use of Baidu face recognition API
- I once met a girl whom I most wanted to take care of all my life. Later... No later
- Talking about kotlin process exception handling mechanism
猜你喜欢

Solution to the eighth training competition of 2020 Provincial Games

Talk about how the kotlin collaboration process establishes structured concurrency

2021-10-20

仿照微信Oauth2.0接入方案

Mysq database remote connection error, remote connection is not allowed

5. Messager framework and imessager interface

Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)

Using appbarlayout to realize secondary ceiling function

Design of mfc+mysql document data management system based on VS2010

I'm late for school
随机推荐
Get to know handler again
JVM family
Explanation on the use of password profiteering cracking tool Hydra
Pit encountered by fastjason
I'm late for school
Reading notes of "Introduction to deep learning: pytoch"
Tutorial for beginners of small programs day01
Six implementation methods of singleton mode
Tclistener server and tcpclient client
Harmonyos actual combat - ten thousand words long article understanding service card development process
So the toolbar can still be used like this? The toolbar uses the most complete parsing. Netizen: finally, you don't have to always customize the title bar!
Recommend a very easy-to-use network communication framework HP socket
ACM intensive training graph theory exercise 3 in the summer vacation of 2020 [problem solving]
qmlplugindump executable not found.It is required to generate the qmltypes file for VTK Qml
Coredata acquisition in swift sorting, ascending, descending
目标检测yolov5开源项目调试
Dart asynchronous task
Interviewer: do you understand the principle of recyclerview layout animation?
Design of mfc+mysql document data management system based on VS2010
Understanding of MVVM and MVC