簡體   English   中英

如何在 React 和 Django Rest 框架中實現自動完成用戶搜索

[英]How to implement autocomplete user search in React and Django Rest Framework

所以基本上我想在反應中實現一個用戶搜索系統,它將向我的 django 后端發送一個 api 請求,該后端將發回結果。 這是一個簡單的實現,如果我想在點擊搜索后得到結果,但我希望結果顯示為自動完成。 例如,在 Twitter 中,它會自動完成您正在搜索的內容。 我將如何實現這一點。 如果有幫助,我正在使用 axios 來滿足我的要求。 附帶說明一下,我想在發送請求之前等待一兩秒鍾,因為我想發送許多請求並減慢服務器的速度。 謝謝!

配方:任意HTTP客戶端(帶/不帶可取消的HTTP客戶端),舉報功能(lodash有一個不錯的),CSS設計套裝顯示你的結果。

Here is the basic idea You create a denounced function and get an instance of that function that can be cancelled, so every time the user hit the search bar we cancel the old subscriptions to that function and resubscribe with new denounced timeout, when that timeout ends我們調用 function 來點擊 API 並獲得響應(代表自動完成響應)以根據需要顯示。

import React, { useState } from 'react';
import axios from 'axios';
import { debounce } from 'lodash';

let debouncedFunction: any;


function App() {

  const [inputValue, setInputValue] = useState('');

  const onSearchChange = (event: any) => {
    try {

      setInputValue(event.target.value);

      /**
       * cancel old saved debounced functions
       */
      if (debouncedFunction && debouncedFunction.cancel)
        debouncedFunction.cancel();

      debouncedFunction = debounce(async () => {

        // use event value if you want in request
        const response: any = await axios.get(
          'https://jsonplaceholder.typicode.com/todos/1' + `?test=${event.target.value}`
        );

        if (response.data) {
          console.log('autocomplete results...')
        }


      }, 2000);
      debouncedFunction();


    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div >

      <input
        value={inputValue}
        onChange={onSearchChange}
        placeholder="Search with autocomplete..."
      />

    </div>
  );
}

export default App;

顯示自動完成結果的 rest 留給您的應用程序顯示更適合您的

這是一個指向 repo 的鏈接,可以根據需要下載和調整

https://github.com/lalosh/stackoverflow-autocomlete-example

很抱歉很忙。 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM