Skip to content

Commit

Permalink
fix: incorrect display when value change from with label to without l…
Browse files Browse the repository at this point in the history
…abel
  • Loading branch information
xulingling0 committed Feb 27, 2024
1 parent 2535b87 commit cb8a623
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
12 changes: 3 additions & 9 deletions src/hooks/useCache.ts
Expand Up @@ -3,42 +3,36 @@ import type { RawValueType } from '../BaseSelect';
import type { DefaultOptionType, LabelInValueType } from '../Select';

/**
* Cache `value` related LabeledValue & options.
* Cache `options` related LabeledValue & options.
*/
export default (
labeledValues: LabelInValueType[],
valueOptions: Map<RawValueType, DefaultOptionType>,
): [LabelInValueType[], (val: RawValueType) => DefaultOptionType] => {
const cacheRef = React.useRef({
values: new Map<RawValueType, LabelInValueType>(),
options: new Map<RawValueType, DefaultOptionType>(),
});

const filledLabeledValues = React.useMemo(() => {
const { values: prevValueCache, options: prevOptionCache } = cacheRef.current;

const { options: prevOptionCache } = cacheRef.current;
// Fill label by cache
const patchedValues = labeledValues.map((item) => {
if (item.label === undefined) {
return {
...item,
label: prevValueCache.get(item.value)?.label,
label: prevOptionCache.get(item.value)?.label,
};
}

return item;
});

// Refresh cache
const valueCache = new Map<RawValueType, LabelInValueType>();
const optionCache = new Map<RawValueType, DefaultOptionType>();

patchedValues.forEach((item) => {
valueCache.set(item.value, item);
optionCache.set(item.value, valueOptions.get(item.value) || prevOptionCache.get(item.value));
});

cacheRef.current.values = valueCache;
cacheRef.current.options = optionCache;

return patchedValues;
Expand Down
17 changes: 17 additions & 0 deletions tests/Select.test.tsx
Expand Up @@ -1885,6 +1885,23 @@ describe('Select.Basic', () => {
expect(findSelection(wrapper).text()).toEqual('903');
});

it('value should be used as label When value does not have a label attribute and historical options do not contain value', () => {
const wrapper = mount(<Select value={{value: 903, label: 'light'}} options={[]} />);
expect(findSelection(wrapper).text()).toEqual('light');

wrapper.setProps({ value: 903 });
expect(findSelection(wrapper).text()).toEqual('903');

wrapper.setProps({ options: [{ value: 903, label: 'Bamboo' }] });
expect(findSelection(wrapper).text()).toEqual('Bamboo');

wrapper.setProps({ value:{ value: 903, label: 'light' },options:[]});
expect(findSelection(wrapper).text()).toEqual('light');

wrapper.setProps({ value: 903, options:[]});
expect(findSelection(wrapper).text()).toEqual('Bamboo');
});

// https://github.com/ant-design/ant-design/issues/24747
// This can not test function called with jest spy, coverage only
it('mouse enter to refresh', () => {
Expand Down

0 comments on commit cb8a623

Please sign in to comment.