Material ui 选择具有异步数据的组件。如何以react hook形式使用它?

问题描述 投票:0回答:1

在我的 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> 
      )

输出为:

如何解决这个问题?

javascript reactjs select material-ui react-hook-form
1个回答
0
投票

据我了解,使用此表达式可以声明

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]);
© www.soinside.com 2019 - 2024. All rights reserved.