import {onBeforeUnmount, watch} from "@peryl/react-compose"; import {createEffects} from "@peryl/utils/createEffects"; /** * watch函数封装,支持清理副作用 * @author 韦胜健 * @date 2022.7.3 13:15 */ export function useWatchAutoClear(watcher: () => T, handler: (newVal: T, oldVal: undefined | T) => (() => void)) { const { effects: setupEffects } = createEffects(); const { effects: watchEffects } = createEffects(); setupEffects.push( watch(() => watcher(), (newVal, oldVal) => { watchEffects.clear(); watchEffects.push( handler(newVal, oldVal) ); }, { immediate: true }) ); onBeforeUnmount(() => { setupEffects.clear(); watchEffects.clear(); }); }