diff --git a/src/OptionList.tsx b/src/OptionList.tsx index aaa9d0ee..bbfa37f9 100644 --- a/src/OptionList.tsx +++ b/src/OptionList.tsx @@ -241,13 +241,15 @@ const OptionList: React.ForwardRefRenderFunction = (_, onKeyUp: () => {}, })); - const loadDataFun = useMemo( - () => (searchValue ? null : (loadData as any)), + const hasLoadDataFn = useMemo( + () => (searchValue ? false : true), [searchValue, treeExpandedKeys || expandedKeys], ([preSearchValue], [nextSearchValue, nextExcludeSearchExpandedKeys]) => preSearchValue !== nextSearchValue && !!(nextSearchValue || nextExcludeSearchExpandedKeys), ); + const syncLoadData = hasLoadDataFn ? loadData : null; + // ========================== Render ========================== if (memoTreeData.length === 0) { return ( @@ -289,7 +291,7 @@ const OptionList: React.ForwardRefRenderFunction = (_, showIcon={showTreeIcon} switcherIcon={switcherIcon} showLine={treeLine} - loadData={loadDataFun} + loadData={syncLoadData} motion={treeMotion} activeKey={activeKey} // We handle keys by out instead tree self diff --git a/tests/Select.loadData.spec.tsx b/tests/Select.loadData.spec.tsx new file mode 100644 index 00000000..c938d95c --- /dev/null +++ b/tests/Select.loadData.spec.tsx @@ -0,0 +1,46 @@ +/* eslint-disable no-undef, react/no-multi-comp, no-console */ +import React from 'react'; +import { render, fireEvent, act } from '@testing-library/react'; + +import TreeSelect from '../src'; + +describe('TreeSelect.loadData', () => { + it('keep sync', async () => { + const Demo = () => { + const [treeData, setTreeData] = React.useState([ + { + title: '0', + value: 0, + isLeaf: false, + }, + ]); + + const loadData = async () => { + const nextId = treeData.length; + + setTreeData([ + ...treeData, + { + title: `${nextId}`, + value: nextId, + isLeaf: false, + }, + ]); + }; + + return ; + }; + + render(); + + for (let i = 0; i < 5; i += 1) { + fireEvent.click(document.querySelector('.rc-tree-select-tree-switcher_close')); + await act(async () => { + await Promise.resolve(); + }); + expect( + document.querySelectorAll('.rc-tree-select-tree-list .rc-tree-select-tree-treenode'), + ).toHaveLength(2 + i); + } + }); +});