From 2108c14634bdcb9fc413ba2df25536eccb72b01c Mon Sep 17 00:00:00 2001 From: zhouyun1 Date: Wed, 14 Sep 2022 15:30:18 +0800 Subject: [PATCH] =?UTF-8?q?fix(CheckSelect):=20=E4=BF=AE=E5=A4=8D=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E5=8A=A0=E8=BD=BD=E6=95=B0=E6=8D=AE=E9=80=89=E4=B8=AD?= =?UTF-8?q?=E9=A1=B9=E6=9C=AA=E7=BC=93=E5=AD=98=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ui/check-select/src/use-check-select.ts | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/ui/check-select/src/use-check-select.ts b/packages/ui/check-select/src/use-check-select.ts index 1aa447f91..be4e9320a 100644 --- a/packages/ui/check-select/src/use-check-select.ts +++ b/packages/ui/check-select/src/use-check-select.ts @@ -4,6 +4,7 @@ import { uniqBy } from '@hi-ui/array-utils' import { useCheck as useCheckDefault } from '@hi-ui/use-check' import { CheckSelectDataItem, CheckSelectItemEventData, CheckSelectMergedItem } from './types' import { useLatestCallback, useLatestRef } from '@hi-ui/use-latest' +import { useCache } from '@hi-ui/use-cache' import { useFlattenData, useData } from './hooks' const NOOP_ARRAY = [] as [] @@ -21,7 +22,8 @@ export const useCheckSelect = ({ ...rest }: UseCheckSelectProps) => { const data = useData({ data: dataProp, children }) - const flattedData = useFlattenData({ data, fieldNames }) + const [cacheData, setCacheData] = useCache(data) + const flattedData = useFlattenData({ data: cacheData, fieldNames }) const flattedDataRef = useLatestRef(flattedData) const [value, tryChangeValue] = useUncontrolledState(defaultValue, valueProp, onChangeProp) @@ -32,6 +34,25 @@ export const useCheckSelect = ({ // 扁平化的选中数据,可能包括异步临时选中缓存数据 const [checkedItems, setCheckedItems] = useState([]) + /** + * 更新缓存的 data 数据 + * 兼容在搜索异步加载结果的场景时,将选中的项加入到 cacheData 数据中,这样再次打开下拉框时可以显示之前选中的值 + */ + const updateCacheData = useCallback( + (nextCheckedItems: any[]) => { + const newData = [...cacheData] + + nextCheckedItems.forEach((item) => { + if (!flattedData.find((dataItem) => dataItem.id === item.id)) { + newData.push('raw' in item ? item.raw : item) + } + }) + + setCacheData(newData) + }, + [cacheData, flattedData, setCacheData] + ) + const proxyTryChangeValue = useCallback( ( value: React.ReactText[], @@ -63,8 +84,11 @@ export const useCheckSelect = ({ changedItems.map((item) => ('raw' in item ? item.raw : item)), nextCheckedItems.map((item) => ('raw' in item ? item.raw : item)) ) + + // 每次更新 value 时,同步更新下 cacheData + updateCacheData(nextCheckedItems) }, - [tryChangeValue, onSelectLatest, flattedDataRef, usedItemsRef] + [flattedDataRef, tryChangeValue, updateCacheData, onSelectLatest] ) const [onOptionCheck, isCheckedId] = useCheckDefault({