| | |
| | | import EditIcon from '@mui/icons-material/Edit'; |
| | | import { useState, useEffect } from 'react'; |
| | | import { useState, useEffect, useMemo } from 'react'; |
| | | import { |
| | | Button, useListContext, SelectInput, |
| | | required, SelectArrayInput, |
| | | useTranslate, useNotify |
| | | } from 'react-admin'; |
| | | import { useFormContext } from 'react-hook-form'; |
| | | import request from '@/utils/request'; |
| | | |
| | | const DictionarySelect = (props) => { |
| | |
| | | } = props; |
| | | const translate = useTranslate(); |
| | | const notify = useNotify(); |
| | | const { watch } = useFormContext(); |
| | | const [list, setList] = useState([]); |
| | | const [loading, setLoading] = useState(false); |
| | | |
| | | // 获取当前表单值 |
| | | const currentValue = watch(name); |
| | | |
| | | useEffect(() => { |
| | | http(); |
| | |
| | | } |
| | | }; |
| | | |
| | | // 确保当前值在选项中,如果不在且正在加载,添加占位选项 |
| | | const choices = useMemo(() => { |
| | | if (!list || list.length === 0) { |
| | | // 如果列表为空但当前有值,添加占位选项以避免警告 |
| | | if (currentValue !== undefined && currentValue !== null && currentValue !== '') { |
| | | return [{ id: currentValue, name: String(currentValue) }]; |
| | | } |
| | | return []; |
| | | } |
| | | |
| | | // 检查当前值是否在选项中 |
| | | const valueExists = list.some(item => String(item.id) === String(currentValue)); |
| | | |
| | | // 如果当前值不在选项中,添加它(可能是加载延迟导致的) |
| | | if (currentValue !== undefined && currentValue !== null && currentValue !== '' && !valueExists) { |
| | | return [...list, { id: currentValue, name: String(currentValue) }]; |
| | | } |
| | | |
| | | return list; |
| | | }, [list, currentValue]); |
| | | |
| | | const InputComponent = multiple ? SelectArrayInput : SelectInput; |
| | | |
| | | return ( |
| | | <InputComponent |
| | | source={name} |
| | | choices={list} |
| | | choices={choices} |
| | | isLoading={loading} |
| | | {...parmas} |
| | | /> |