MUI 和 Formik 自动完成多个

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

我在使用 Formik 和 MUI 自动完成处理多个项目时遇到问题。 有时,它无法正确突出显示所选项目,特别是在搜索该项目后。还有一个问题是它可以选择已经被选择的项目。

预期结果: 我们将能够选择一个或多个项目。当选择一个项目时,其复选框将被选中,并且它会突出显示。

这是我的代码和框:CODESANDBOX

注意: 最好用真实的 API 来测试它,但我在这里使用真实的 API 时遇到了困难。

const TestAutocomplete = ({
  field,
  form: { touched, errors, setFieldValue, values },
  ...props
}) => {
  const [inputValue, setInputValue] = useState("");
  const debouncedInputValue = useDebounceValue(inputValue, 500);

  const { data: response, isLoading } = useFetchSubledgersQuery({
    pageNumber: 0,
    pageSize: 50,
    search: debouncedInputValue,
  });

  const handleChange = (_, newSelectedValues, reason) => {
    if (reason === "clear") {
      setFieldValue(field.name, []);
      return;
    }

    setFieldValue(field.name, newSelectedValues);
  };

  const handleInputChange = (_, newInputValue) => {
    setInputValue(newInputValue);
  };

  return (
    <Autocomplete
      {...field}
      multiple
      getOptionLabel={(option) =>
        typeof option === "string" ? option : option?.name || ""
      }
      filterOptions={(x) => x}
      options={response || []}
      autoComplete
      includeInputInList
      fullWidth
      noOptionsText={isLoading ? "Loading..." : "No data"}
      onChange={handleChange}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      renderInput={(params) => (
        <TextField
          {...params}
          {...props}
          error={touched[field.name] && errors[field.name] ? true : false}
          helperText={
            touched[field.name] &&
            errors[field.name] &&
            String(errors[field.name])
          }
        />
      )}
      renderOption={(props, option, { selected }) => (
        <li {...props}>
          <Checkbox
            icon={icon}
            checkedIcon={checkedIcon}
            style={{ marginRight: 8 }}
            checked={values?.[field.name]?.some(
              (selectedValue) => selectedValue.id === option.id
            )}
          />
          {option?.name}
        </li>
      )}
      renderTags={(value, getTagProps) =>
        value.map((option, index) => (
          <Chip
            key={option.id}
            label={option.name}
            {...getTagProps({ index })}
          />
        ))
      }
    />
  );
};
reactjs ecmascript-6 material-ui formik
1个回答
0
投票

问题是,当您输入“自动完成”功能时,对

useFetchSubledgersQuery()
的调用会再次运行,并且您会返回与
id
中的值完全不同的一组
response
数字。

在输入自动完成功能之前,我有以下值:

在自动完成中仅输入字母“s”后,我得到了以下值:

这会导致控制台中出现警告:

index.js:8 MUI: The value provided to Autocomplete is invalid.
None of the options match with `{"id":564863,"name":"Subledger 1"}`.
You can use the `isOptionEqualToValue` prop to customize the equality test. 

因为该值不再出现在选项列表中。

© www.soinside.com 2019 - 2024. All rights reserved.