简体   繁体   English

仅当用户在 React 中按搜索或 Enter 时才获取数据?

[英]Only fetch the data if user press search or Enter in React?

I've set up a search Bar to fetch the data from the backend and return it.我已经设置了一个搜索栏来从后端获取数据并返回它。

CODE:代码:

const App = () => {

const[datas,setDatas] = useState([])   //NOthing to do with this.

const [space,setSpace] = useState(null)
const [print, setPrint] = useState(false)


function getData(val){
  console.log(val.target.value)
  setSpace(val.target.value);
  setPrint(false)
}

console.log(space)  //Returning inputted text in console. Works well

  useEffect(() => {
    const fecthPosts = async () => {
      let initial_url = `http://localhost:4000/search` 
      let url = initial_url + "?text=" + space  
       
       const res = await fetch(url);
       const {result} = await res.json();

     setDatas(result);
    fecthPosts();
  },[space]);

return(
<div className="App">
     {                  //Displaying on search
        print?
         <>
        <h2>{space}</h2>  //submited text
        <div> 
       {results.map((field) => 
       <p>{field.title}</p> 
       <p>{field.author}</p> 
       )}
        </div>
        </>
        :null
      }
   <input type="text" onChange={getData} />
 <button onClick={() => setSpace(true)}>search</button>
</div>
  )
 }
};

export default App;

Now, this code works perfectly fine.现在,这段代码工作得很好。 But when I click on Network Tab then,但是当我点击Network Tab

It's fetching data from every text I'm typing.它从我输入的每个文本中获取数据。 Problems with onChange onChange问题

search?text=s
search?text=sa  
search?text=sam 
search?text=sams
search?text=samsu   
search?text=samsun
search?text=samsung

I don't want this to be happen because I've got limited No. of requests to send.我不希望这种情况发生,因为我要发送的请求数量有限。

Anyone plz help to solve this issue.I've tried several things but nothing working...任何人都可以帮助解决这个问题。我尝试了几件事,但没有任何效果......

NOTE: I can't use Timeout and any other method which works... only search or fetch data if user press enter or click the button .注意:我不能使用Timeout和任何其他有效的方法......只有在用户press enterclick the button时才搜索或获取数据。

You can fetch inside a short timeout (say, after 2 seconds of inactivity after typing) with a ref.您可以在很短的超时时间内(例如,在输入后 2 秒不活动后)使用 ref 进行提取。

Don't ignore possible errors either - unhandled rejections should always be avoided.也不要忽略可能的错误 - 应始终避免未经处理的拒绝。

const timeoutRef = useRef();
useEffect(() => {
    const doFetch = () => {
        const url = 'http://localhost:4000/search?text=' + space
        fetch(url)
            .then(res => res.json())
            .then(({ result }) => setDatas(result))
            .catch(handleErrors); // don't forget this
    };
    clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(doFetch, 2000);
}, [space]);

I think there are some issues with the code, for example when showing the search result, if I understand correctly:我认为代码存在一些问题,例如在显示搜索结果时,如果我理解正确的话:

{results.map((field) => 

should be应该

{datas.map((field) => 

right?对?

For your current problem,对于您目前的问题,

  1. You're calling the search API every time when the input text is changed.每次更改输入文本时,您都会调用搜索 API。
  2. Only show the search result when the search button is clicked.仅在单击search按钮时显示搜索结果。

So why not only trigger the API call when the search button is clicked?那么为什么不只在点击search按钮时触发 API 调用呢?

您可以使用 denounce,仅在 n 秒后调用搜索 API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM