跳到主要内容

useMountEffect

2024年02月28日
柏拉文
越努力,越幸运

一、认识


useMountEffect 用于多个状态变化满足到一定条件后, 执行一次回调

二、实现


import { useRef, useEffect } from 'react';

function useMountEffect(depsFn: Function, effectFn: Function) {
const isMounted = useRef(true);

useEffect(() => {
if (isMounted.current && depsFn()) {
effectFn();
isMounted.current = false;
}
}, [depsFn]);
}

export default useMountEffect;

三、测试


import { useEffect, useState } from 'react';
import useMountEffect from './hooks/useMountEffect';

function App() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);

useMountEffect(
() => a === 3 && b === 2,
() => console.log('a,b 满足条件之后的初始化', a + b)
);

useEffect(() => {
setTimeout(() => {
setA(3);
}, 3000);

setTimeout(() => {
setB(2);
}, 5000);
}, []);

return <>实现依赖变化满足一定条件之后的初始化 Hook</>;
}

export default App;