如何消除 mui 自动完成

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

我需要去抖动

onInputChange
功能

export interface AutocompleteProps<V extends FieldValues> {
  onInputChange: UseAutocompleteProps<UserOrEmail, true, false, false>['onInputChange'];
}
export default function MyAutocomplete<V extends FieldValues>({
  onInputChange
}: AutocompleteProps<V>) {

  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { onChange, value } }) => (
        <Autocomplete<UserOrEmail, true, false, false>

          onInputChange={onInputChange} //here

        />
      )}
    />
  );

我已经这样做了(在外面使用了去抖动并像道具一样传递它)并且它有效

const [search, setSearch] = useState('');
const searchDelayed = useCallback(
    debounce((newValue: string) => setSearch(newValue), 100),
    []
  );
      //Passing the prop like this
        /*
           onInputChange={(_, newValue) => {
                        searchDelayed(newValue);
                      }}
        */

我想在

MyAutocomplete
中去抖但是我不能在
onInputChange
函数中调用
debounce
。如果我不调用它,那么我会得到一个错误,并且它不起作用

const searchsDelayed = useCallback( //does not work
     debounce(() => onInputChange, 100),
    [onInputChange]
  );

有什么办法可以做到吗?

reactjs typescript
2个回答
2
投票

[审查答案以避免混淆。]

主要问题在这里:

debounce(() => onInputChange, 100);

你正在对一个返回

onInputChange
的函数去抖动,它不会调用它,并且需要调用它两次。 要解决这个问题,只需直接传递
onInputChange

debounce(onInputChange, 100);

无论如何,你正在尝试使用

useCallback
但你可能不需要任何优化就可以了,所以你可以使用

const searchDelayed = debounce(onInputChange, 100);

但是如果你真的需要优化,在这种情况下你应该使用

useMemo
因为你需要 debounce 调用的结果:

const searchDelayed = useMemo(
    () => debounce(onInputChange, 100),
    [onInputChange]
);

0
投票

有一个内置的 MUI 去抖实用程序可供使用。你可以这样导入

import { debounce } from '@mui/material/utils'

你可以在这里找到官方 MUI 实现示例MUI Autocomplete with debounce

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