From 4a145ba7f21b64a40cd3c927c828da51a3cc86b5 Mon Sep 17 00:00:00 2001 From: xzdry Date: Fri, 5 May 2023 17:33:38 +0800 Subject: [PATCH] fix(collapse): fix infinite loop caused by defaultValue as an array --- .../arco-lib/src/hooks/useDeepCompareEffect.ts | 18 ++++++++++++++++++ packages/arco-lib/src/hooks/useStateValue.ts | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 packages/arco-lib/src/hooks/useDeepCompareEffect.ts diff --git a/packages/arco-lib/src/hooks/useDeepCompareEffect.ts b/packages/arco-lib/src/hooks/useDeepCompareEffect.ts new file mode 100644 index 00000000..a2f2a326 --- /dev/null +++ b/packages/arco-lib/src/hooks/useDeepCompareEffect.ts @@ -0,0 +1,18 @@ +import { useEffect, useRef } from 'react'; +import isEqual from 'lodash/isEqual'; + +const useDeepCompareEffect = ( + effect: React.EffectCallback, + deps: React.DependencyList +) => { + const prevDeps = useRef(null); + + useEffect(() => { + if (prevDeps.current && !isEqual(deps, prevDeps.current)) { + effect(); + } + prevDeps.current = deps; + }, [deps, effect]); +}; + +export default useDeepCompareEffect; diff --git a/packages/arco-lib/src/hooks/useStateValue.ts b/packages/arco-lib/src/hooks/useStateValue.ts index c349e5fb..6e1c34ae 100644 --- a/packages/arco-lib/src/hooks/useStateValue.ts +++ b/packages/arco-lib/src/hooks/useStateValue.ts @@ -1,6 +1,7 @@ import { RuntimeFunctions } from '@sunmao-ui/runtime'; import { useState, useEffect } from 'react'; import { SlotSpec } from '@sunmao-ui/core'; +import useDeepCompareEffect from './useDeepCompareEffect'; export const useStateValue = < T, @@ -22,7 +23,7 @@ export const useStateValue = < // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - useEffect(() => { + useDeepCompareEffect(() => { if (updateWhenDefaultValueChanges && mergeState) { setValue(defaultValue); mergeState({ [key]: defaultValue });