每次击键都会调用 api [英] api call with every key stroke

查看:36
本文介绍了每次击键都会调用 api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建这个 React 网站,我可以在其中搜索一个地方.每当我在搜索框中输入新字母时,都会出现问题,调用 api 会使网站速度变慢.我不希望它每次击键都调用 api.我认为这是因为第二个 useEffect 但如果我删除该 useEffect 则搜索结果中不会显示任何结果.我该如何解决这个问题.在类组件中,我认为我们可以使用 componentDidUpdate 来实现,但在这里我使用了 useEffect 但没有得到想要的结果.

I tried to create this react website where I can search for a place. I'm having a problem cause whenever I enter a new letter in the search box, the api is called which is making the website very slow. I don't want it to call the api with every keystroke. I think this is because of the second useEffect but if I remove that useEffect then no results are displayed in the search results. How can I tackle this problem. in class component I think we can do it with componentDidUpdate but here I used useEffect but not getting the desired result.

这是代码

App.js

  useEffect(() => {
    getItems();

    if (finalSearch) {
      filterData();
    } else {
      handleRequest();
    }
  }, [search, finalSearch]);

 

推荐答案

看起来你在开始时调用了 api,然后一旦搜索组件有值,你就过滤数据.

It looks like you call the api at the beginning and then once the search component has values, you filter the data.

如果您想在每次击键时停止获取 API,只需删除 useEffect 中的 else 子句即可.

If you want to stop fetching the API on each keystroke, just remove the else clause in your useEffect.

  useEffect(() => {
    getResults();

    if (finalSearch) {
      filterData();
    }
  }, [search, finalSearch]);

这篇关于每次击键都会调用 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆