繁体   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