Lodash 去抖 async/await

Lodash debounce async/await

我试图在执行 api 调用之前向我的应用程序添加去抖动。但是,当我引入 debouce 时,似乎我的 await 被忽略了,并且由于缺少值

而调用了函数
export default class App extends Component {
  state = {
    search: "Cats",
    results: []
  };

  async search(text) {
    const giphy = {
      baseURL: "https://api.giphy.com/v1/gifs/search",
      apiKey: "0UTRbFtkMxAplrohufYco5IY74U8hOes",
      tag: text
    };

    let giphyURL = encodeURI(
      giphy.baseURL + "?api_key=" + giphy.apiKey + "&q=" + giphy.tag
    );

    let data = await fetch(giphyURL);
    return data.json();
  }

  async componentDidMount() {
    // get default search
    this.onSearch(this.state.text);
  }

  setSearch = e => {
    this.setState({ search: e.target.value });

    debounce(() => this.onSearch(this.state.search), 100);
  };

  async onSearch(text) {
    console.log("text:", text);
    try {
      let response = await this.search(this.state.search);
      console.log("data:", response.data);
      // console.log(data.results);

      let data = response.data.reduce((t, { title, id, images }) => {
        t.push({ title, id, url: images.downsized_medium.url });
        return t;
      }, []);
      this.setState({ results: data });
    } catch (e) {
      console.error("Failed Fetch", e.toString());
    }
  }

  render() {
    return (
      <main className="app">
        <Header>This is my Gif Search App</Header>
        <nav className="navbar">
          <SearchBox onSearch={this.setSearch} value={this.state.search} />
        </nav>
        <aside className="sidebar">Sidebar Bar</aside>
        <section className="results">
          <Results results={this.state.results} />
        </section>
        <footer className="footer">
          <p className="footer-text">Copyright @funssies 2019</p>
        </footer>
      </main>
    );
  }
}

错误:在 setSearch 方法中,我将获取数据的调用包装在 debounce 中,但没有任何反应。

onSearch 是一个异步函数。 debounce 的参数函数也必须是异步的。是的,就像蝙蝠侠指出的那样。

const debouncedOnSearch = debounce(async () => {
         this.onSearch(this.state.search)
    }, 100);
setSearch = e => {
    this.setState({ search: e.target.value });
    debouncedOnSearch();

  };

这应该有效。另一个类似的问题我.

希望对您有所帮助。

我想我明白了。 Deboune returns 一个函数。然后我必须调用那个函数

例如:

let myFunc = debounce(this.someFunction,100)

// call debounced function 
myFunc()

我将我的功能更改为:

  delayedSearch = debounce(this.onSearch, 1500);

  setSearch = e => {
    this.setState({ search: e.target.value });

    this.delayedSearch(this.state.search);
  };

在这里找到帮助:lodash debounce not working in anonymous function

这是一个简单的异步版本(适用于 debounce npm)

export default function MyComponent() {
    const [searchTerm, setSearchTerm] = useState('');
    const launchSearch = async (searchValue: string): Promise<any> => {
        console.log(searchValue);
    };

    const delayedSearch = useCallback(
        debounce(async (searchTerm) => {
            await launchSearch(searchTerm);
        }, 2000),
        []
    );
    useEffect(() => {
        if (searchTerm.length >= 2) {
            delayedSearch(searchTerm);
        }
    }, [searchTerm]);

    ... 
}

除了上述答案之外,如果您的 throttled/debounced 处理程序使用 props 或 state,如下所示:

const { fetcherFunctionFromProps } = props;

const eventHandler = async () => {
  const resp = await fetcherFunctionFromProps();
};    

const debouncedEventHandler = useMemo(
  () => throttle(eventHandler, 300)
), [fetcherFunctionFromProps]);

而且它不起作用,
您可以将其重构为以下内容:

const { fetcherFunctionFromProps } = props;

const eventHandler = async (fetcher) => {
  const resp = await fetcher();
};

const debouncedEventHandler = useMemo(() => throttle(eventHandler, 300), []);
...
<Component onClick={() => debouncedEventHandler(fetcherFunctionFromProps)}>