refactor: try reduce

This commit is contained in:
sealday 2024-03-22 03:15:43 +08:00
parent e8497f8f8e
commit 25e41e479e

View File

@ -4,12 +4,6 @@ import { connect, useFieldSchema } from '@formily/react';
import { useCollectionManager, useRequest } from '@nocobase/client'; import { useCollectionManager, useRequest } from '@nocobase/client';
import _ from 'lodash'; import _ from 'lodash';
interface Option {
name: string | number;
id: string;
children?: Option[];
}
const AssociationCascader = connect((props) => { const AssociationCascader = connect((props) => {
const fieldSchema = useFieldSchema(); const fieldSchema = useFieldSchema();
const collection = fieldSchema['collectionName']; const collection = fieldSchema['collectionName'];
@ -32,24 +26,20 @@ const AssociationCascader = connect((props) => {
}); });
const options = useMemo(() => { const options = useMemo(() => {
const dict = {}; const dict: { [key: string]: string[] } =
data?.data.forEach((item) => { data?.data.reduce((acc, item) => {
if (item[associationField]) { if (item[associationField]) {
dict[item[associationField][joinTitleField]] ??= []; const key = item[associationField][joinTitleField];
dict[item[associationField][joinTitleField]].push(item[titleField]); acc[key] ??= [];
} acc[key].push(item[titleField]);
}); }
const options: Option[] = []; return acc;
_.forEach(dict, (values: any, key) => { }, {}) || {};
options.push({ const options = Object.entries(dict).map(([key, values]) => ({
name: key, name: key,
id: key, id: key,
children: values.map((value) => ({ children: values.map((value) => ({ name: value, id: value })),
name: value, }));
id: value,
})),
});
});
return options; return options;
}, [associationField, joinTitleField, titleField, data?.data]); }, [associationField, joinTitleField, titleField, data?.data]);
return <Cascader options={options} {...props} showSearch />; return <Cascader options={options} {...props} showSearch />;