重大ui自动完成onChange不会更新值

时间:2020-05-31 14:08:31

标签: reactjs react-redux material-ui react-hooks react-material-ui-form-validator

我已经使用(Material-Ui Autocomplete)创建了一个通用的下拉菜单组件,因此可以在需要的地方使用。但是我遇到了一个问题,自动完成功能不会更新“更改”上的值

注意

我遵循了不同的链接,但没有得到正确的答案,我的情况略有不同。我有 创建了一个通用的下拉菜单组件,并在需要的其他组件内部使用。

这是下拉菜单组件的代码

import React, { memo, useEffect } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CircularProgress from "@material-ui/core/CircularProgress";
import { useDispatch } from "react-redux";    

interface IAsyncDropDownMenu {
  title: string;
  id?: string;
  loadData: Function;
  onSelect(value: any): void;
  fieldError: {
    error: false,
    label: "",
    helperText: "",
    validateInput: false,
    };
}    

interface IOptionTypes {
  id: number;
  name: string;
}    

const AsyncDropDownMenu: React.FC<IAsyncDropDownMenu> = memo(
  ({
    title,
    id = "asynchronous-dropdown-menu",
    loadData,
    onSelect,
    fieldError,
  }) => {
    const [open, setOpen] = React.useState(false);
    const [options, setOptions] = React.useState<IOptionTypes[]>([]);
    const loading = open && options.length === 0;
    const [selectedOption, setSelectedOption] = React.useState<any>({
      id: 0,
      name: "",
    });    

    const dispatch = useDispatch();    

    const seletOption = (value: any) => {
      onSelect(value);
    };
    useEffect(() => {
      let active = true;
      if (!loading) {
        return undefined;
      }
      (async () => {
        const data = await dispatch(loadData());
        if (active) {
          setOptions(data);
        }
      })();    

      return () => {
        active = false;
      };
    }, [loading]);    

    useEffect(() => {
      if (!open) {
        setOptions([]);
      }
    }, [open]);    

    return (
      <Autocomplete
        id={id}
        open={open}
        onOpen={() => {
          setOpen(true);
        }}
        onClose={() => {
          setOpen(false);
        }}
        onChange={(event, value) => seletOption(value)}
        getOptionSelected={(option, value) => option.name === value.name}
        getOptionLabel={(option) => option.name}
        options={options}
        loading={loading}
        renderInput={(params) => (
          <TextField
            {...params}
            label={title}
            helperText={fieldError.helperText}
            error={fieldError.error}
            InputProps={{
              ...params.InputProps,
              endAdornment: (
                <>
                  {loading ? (
                    <CircularProgress color="inherit" size={20} />
                  ) : null}
                  {params.InputProps.endAdornment}
                </>
              ),
            }}
          />
        )}
      />
    );
  }
);    

export { AsyncDropDownMenu };

这是我在其中使用下拉菜单组件的Component的代码

const ProductSubCategory: React.FC = () => {
const classes = CommonStyle();
const subCatList=[];
const dispatch = useDispatch();

//#region error states and function
const [selectedOption, setSelectedOption] = React.useState({
   id: 0,
    name: "",
});

const [categoryError, setCategoryError] = React.useState({
  error: false,
  label: "",
  helperText: "",
  validateInput: false,
});
const onError = (action: Function, message: string = "Required field") => {
  action({
     error: true,
     label: "required",
     helperText: message,
     validateInput: true,
 });
};

//#endregion

const onselect = (value: any) => {
 if (categoryError.validateInput) {
   setCategoryError({
     error: false,
     label: "",
     helperText: "",
     validateInput: false,
   });
 }
 setSelectedOption(value);
};

//#region grid columns
const columns = [
  {
   title: "Category",
   render: (rowData: ITemp) => {
     return rowData.categories ? rowData.categories.name : "";
   },
   field: "category",
   lookup: {},
   editComponent: (props: any) => (
     <AsyncDropDownMenu
       title="Category"
       loadData={loadCategories}
       onSelect={onselect}
       fieldError={categoryError}
     ></AsyncDropDownMenu>
   ),
 },   
];

//#endregion

//#region validate input data
const onValidate = (
  data: any,
  reject: Function,
  resolve: Function,
  action: Function,
 isUpdate: boolean,
 oldData: any
) => {
  if (Object.keys(data).length === 0 && selectedOption.id === 0) {
    onError(setNameError);
    onError(setCategoryError);
    reject();
  } else if (selectedOption.id === 0) {
    onError(setCategoryError);
    reject();
  } else {

    if (isUpdate) {
      if (data !== oldData) dispatch(action(data, reject, resolve));
      else reject();
    } else {
      dispatch(action(data, reject, resolve));
    }
  }
};

//#endregion


return (
 <div>
   <CustomMatrialTable
     title="Product Sub Categories"
     isLoading={isLoading}
     col={columns}
     data={subCatList}
   ></CustomMatrialTable>
 </div>
);
};
export { ProductSubCategory };

在所附的图像问题中,我已经显示出问题。 Dropdown value not update on select

0 个答案:

没有答案