common-hook
Version:
提供项目中常用的 React Hooks
55 lines (54 loc) • 1.94 kB
JavaScript
import { useRef } from "react";
import { useUnmount } from "common-hook";
import depsAreSame from "./depsAreSame";
import { getTargetElement } from "./domTarget";
const createEffectWithTarget = (useEffectType) => {
/**
*
* @param effect
* @param deps
* @param target target should compare ref.current vs ref.current, dom vs dom, ()=>dom vs ()=>dom
*/
const useEffectWithTarget = (
// @ts-ignore
effect,
// @ts-ignore
deps, target) => {
const hasInitRef = useRef(false);
// @ts-ignore
const lastElementRef = useRef([]);
// @ts-ignore
const lastDepsRef = useRef([]);
// @ts-ignore
const unLoadRef = useRef();
useEffectType(() => {
var _a;
const targets = Array.isArray(target) ? target : [target];
const els = targets.map((item) => getTargetElement(item));
// init run
if (!hasInitRef.current) {
hasInitRef.current = true;
lastElementRef.current = els;
lastDepsRef.current = deps;
unLoadRef.current = effect();
return;
}
if (els.length !== lastElementRef.current.length ||
!depsAreSame(els, lastElementRef.current) ||
!depsAreSame(deps, lastDepsRef.current)) {
(_a = unLoadRef.current) === null || _a === void 0 ? void 0 : _a.call(unLoadRef);
lastElementRef.current = els;
lastDepsRef.current = deps;
unLoadRef.current = effect();
}
});
useUnmount(() => {
var _a;
(_a = unLoadRef.current) === null || _a === void 0 ? void 0 : _a.call(unLoadRef);
// for react-refresh
hasInitRef.current = false;
});
};
return useEffectWithTarget;
};
export default createEffectWithTarget;