在我的 React 应用程序中,我使用react-hook-form 和 Material UI。我有这样的情况。需要显示一个包含值列表的下拉菜单。该值列表是从 API 响应中获取的。另一个 API 正在获取之前存储的值。我的问题是最初没有选择保存值的下拉列表。
我拥有的是:
const { data: allCountryList } = useGetCountryList(); // Fetching entire countrylist
const countryList = useMemo(() => { //Processing the countrylist
const list = allCountryList?.result?.countryList?.map((country) => ({
label: country?.name,
value: country?.code,
}));
return list;
}, [allCountryList]);
const fetchDetails = useCallback(async () => {
const response = await getProfileDetails(); // getting previously saved values
const {
email = '',
.........
country = '',
} = response?.result?.user ?? '';
response?.result?.user?.companies;
return {
email,
.........
country,
};
}, []);
const {
control,
setValue,
formState: { errors },
watch,
trigger,
getValues,
reset,
setError,
} = useForm<FormDataType>({
resolver: yupResolver(schema),
defaultValues: fetchDetails,
shouldFocusError: true,
mode: 'all',
});
......
return(
....................
<FormControl sx={{ display: 'flex', marginBottom: '0' }}>
<Controller
name="country"
control={control}
render={({ field }) => (
<Select
id="country"
label="country
aria-label="country"
required
displayEmpty
MenuProps={{ sx: { maxHeight: 200 } }}
{...field}
error={!!errors?.country?.message}
helperText={errors?.country?.message}
onChange={onCountryChange}
>
<MenuItem value="" disabled>
{t('fields.country')}
</MenuItem>
{countryList?.map((country, index) => (
<MenuItem value={country.value} key={`${country.value} - ${index}`}>
{country.label}
</MenuItem>
))}
</Select>
)}
/>
</FormControl>
)
如何解决这个问题?
据我了解,使用此表达式可以声明
data
常量,并使用值 allCountryList
: 对其进行初始化
const { data: allCountryList } = useGetCountryList(); // Fetching entire countryli
因此,你应该有这样的东西:
const countryList = useMemo(() => { //Processing the countrylist
const list = data?.result?.countryList?.map((country) => ({
label: country?.name,
value: country?.code,
}));
return list;
}, [data]);