umijs hook

import { DependencyList, useState, useMemo, useRef, useCallback } from 'react';
import useUpdateEffect from '../useUpdateEffect';
import useDebounceFn from '../useDebounceFn';

import useAsync from '../useAsync';

export interface ReturnValue<T> {
  loading: boolean;
  data?: T;
  value: any;
  onChange: (value: any) => void;
  cancel: () => void;
  run: () => void;
}

export interface Options {
  wait?: number;
}

function useSearch<Result>(
  fn: (value: any) => Promise<Result>,
  options?: Options,
): ReturnValue<Result>;
function useSearch<Result>(
  fn: (value: any) => Promise<Result>,
  deps?: DependencyList,
  options?: Options,
): ReturnValue<Result>;
function useSearch<Result>(
  fn: (value: any) => Promise<Result>,
  deps?: DependencyList | Options,
  options?: Options,
): ReturnValue<Result> {
  const _deps: DependencyList = (Array.isArray(deps) ? deps : []) as DependencyList;
  const _options: Options = (typeof deps === 'object' && !Array.isArray(deps)
    ? deps
    : options || {}) as Options;

  const [value, setValue] = useState<any>('');

  const { loading, data, run, cancel: cancelAsync } = useAsync<Result>(fn, [value, ..._deps], {
    manual: true,
  });

  const wait: number = useMemo(() => (_options.wait === undefined ? 300 : _options.wait), [
    _options.wait,
  ]);

  const debounce = useDebounceFn(
    () => {
      run(value);
    },
    [value],
    wait,
  );

  
  useUpdateEffect(() => {
    run(value);
  }, _deps);

  const cancel = useCallback(() => {
    
    debounce.cancel();
    
    cancelAsync();
  }, [cancelAsync, debounce.cancel]);

  
  const trigger = useCallback(() => {
    run(value);
  }, [run, value]);

  return {
    data,
    loading,
    value,
    onChange: setValue,
    cancel,
    run: trigger,
  };
}

export default useSearch;

截取部分源码 请问这个function useSearch 定义了多次的作用是什么?

待解决 悬赏分:30 - 离问题结束还有 344天2小时40分55秒
反对 0举报 0 收藏 0

我来回答

回答1