reactjs 我不知道如何创建一个功能搜索栏django/react

yhived7q  于 2022-11-29  发布在  React
关注(0)|答案(2)|浏览(117)

在我的电子商务项目中,我想实现一个搜索栏,在那里你可以通过drf api按名称搜索产品,我安装了django_filters并创建了一个类,如下所示:

class ProductFilter(generics.ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['^name']

我测试了端点,它可以工作,但我不知道如何让它在react的前端部分工作,我在标题中有一个saerchbar,如下所示:

<Form className="d-flex">
 <Form.Control
   type="search"
   placeholder="Search"
   className="me-2"
   aria-label="Search"
 />
 <Button variant="outline-success">Search</Button>
</Form>

使用axios进行api调用,我不知道如何设置,如果我需要reducer,actions,store

vybvopom

vybvopom1#

我认为你可以创建一个函数,当用户输入任何文本时,它将调用api。同时,去抖动它,以避免频繁的api调用。

import React, { useCallback } from "react";

// Debounce to avoid frequent api calls
export const debounce = (func, waitFor) => {
  let timeout = null;

  const debounced = (...args) => {
    if (timeout !== null) {
      clearTimeout(timeout);
      timeout = null;
    }
    timeout = setTimeout(() => func(...args), waitFor);
  };

  return debounced;
};

const TestComponent = () => {
  // debounce the function so that we send api calls once user stops typing
  const searchSomething = useCallback(
    debounce(async (value) => {
      try {
        // Make your api call using whichever library you are using
        // let response = await fetch(`${YOUR_SERVER_URL}/search?query=${value}`);
        let response =  axios.get(`${YOUR_SERVER_URL}/search?query=${value}`)
        console.log(response);
      } catch (error) {
        console.log(error);
      }
    }, 500),
    []
  );

  return (
    <Form className="d-flex">
      <Form.Control
        type="search"
        placeholder="Search"
        className="me-2"
        aria-label="Search"
        onChange={(e) => {
          searchSomething(e.target.value);
        }}
      />
      <Button variant="outline-success">Search</Button>
    </Form>
  );
};

export default TestComponent;
bgibtngc

bgibtngc2#

您的axios调用应该以如下方式结束:

axios({
  method: 'post',
  url: '/login', // replace with your endpoint URL
  data: {
    searchField.name: searchField.value,
  }
});

其中searchField.name是Django希望在后端接收到的字段名(这里看起来是name),searchField.value是搜索字段的值。

相关问题