如何在React Native应用程序中构建搜索功能?

问题描述 投票:0回答:1

我有一个反应本机应用程序。而且我有一个搜索功能。我面临的问题是搜索功能仅在文本字段中输入整个单词时才起作用。

例如 Edelhert 就可以工作。但如果用户输入:Ed - 那么什么也不会发生。

如果用户在搜索文本字段中等待一秒钟。然后弹出这个错误:

VM270:1  Uncaught SyntaxError: Unexpected identifier 'Promise'

所以搜索 api 看起来是:

import { API_URL } from "@env";
import { retrieveToken } from "../../services/authentication/token";

export const fetchAnimalData = async (text) => {
    const token = await retrieveToken();
    try {
        if (token) {
            const response = await fetch(`${API_URL}/api/animals/?name=${text}`, {
                method: "GET",
                headers: {
                    Authorization: `Token ${token}`,
                    Accept: "application/json",
                    "Content-Type": "application/json",
                },
            });
            return await response.json();
        } else {
            throw new Error(token);
        }
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

和搜索上下文:

/* eslint-disable prettier/prettier */

import React, { createContext, useEffect, useState } from "react";
import { fetchAnimalData } from "./animal/animal.service";
export const SearchAnimalContext = createContext();
export const SearchAnimalContextProvider = ({ children }) => {
    const [searchAnimal, setSearchAnimal] = useState([]);
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [input, setInput] = useState("");

    useEffect(() => {
        fetchAnimalData();
    }, [searchAnimal]);

    const performSearch = async (text) => {
        setLoading(true);
        setError(null);
        setTimeout(() => {
            fetchAnimalData(text)
                .then((response2) => {
                    setResults(response2);
                    setLoading(false);
                })
                .catch((err) => {
                    setLoading(false);
                    setError(err);
                });
        });
    };
    return (
        <SearchAnimalContext.Provider
            value={{
                results,
                setResults,
                searchAnimal,
                setSearchAnimal,
                input,
                setInput,
                performSearch,
                loading,
                error,
            }}>
            {children}
        </SearchAnimalContext.Provider>
    );
};

还有带有搜索字段的组件:

import React, { useContext, useState } from "react";

import { AccordionItemsContext } from "../../../services/accordion-items.context";
import { AnimalDetailToggle } from "../../../components/general/animal-detail-toggle-view";
import { CategoryContext } from "../../../services/category/category.context";
import { CategoryInfoCard } from "../components/category-info-card.component";
import { SafeArea } from "../../../components/utility/safe-area.component";
import { SearchAnimalContext } from "../../../services/search-animal.context";
import { Searchbar } from "react-native-paper";

export const CategoryScreen = ({ navigation }) => {
    useContext(AccordionItemsContext);  
    const { loading, categoryList } = useContext(CategoryContext);
    const { performSearch, results, setInput, input } = useContext(SearchAnimalContext);
    const [searchTimer, setSearchTimer] = useState(null);

    return (
        <SafeArea>
            {loading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.blue500} />
                </LoadingContainer>
            )}
            <Searchbar
                placeholder="search animalll"
                onChangeText={(text) => {
                    if (searchTimer) {
                        clearTimeout(searchTimer);
                    }
                    if (!text.length) {
                        setInput("");
                        return;
                    }

                    setInput(text.substring(0));
                    setSearchTimer(setTimeout(performSearch(text), 1000));
                }}
                value={input}
            />

        </SafeArea>
    );
};

对于后端,我使用 django。其中一种观点是这样的:

from django_filters.rest_framework import DjangoFilterBackend
# from DierenWelzijnAdmin.permissions import AdminReadOnly
from rest_framework import permissions, viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.contrib.auth.decorators import permission_required
from rest_framework import filters

from .models import Animal, Category
from .serializers import (AnimalSerializer, CategorySerializer,
                          MainGroupSerializer)


class AnimalViewSet(viewsets.ModelViewSet, permissions.BasePermission):

    queryset = Animal.objects.all().order_by('name')
    serializer_class = AnimalSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]

    filterset_fields = ['name']
    search_fields = ['name']


class CategoryViewSet(viewsets.ModelViewSet, permissions.BasePermission):
    """
    This API endpoint allows for the viewing of animal categories.

    All categories include their direct subcategories and animals.

    - To view a specific category, append the url with its [/id](/api/categories/1/).
    - To get all top-level categories use [/main_groups](/api/categories/main_groups). 
    """

    def get_serializer_class(self):
        if hasattr(self, 'action') and self.action == 'main_groups':
            return MainGroupSerializer
        return CategorySerializer

    queryset1 = Category.objects.all().order_by('name')
    queryset = CategorySerializer.eager_load(queryset1)
    serializer_class = get_serializer_class(super)

    permission_classes = (IsAuthenticated,)

    @action(methods=['get'], detail=False)
    # @permission_required("category")
    def main_groups(self, request):
        """
        Returns a list of top level Categories.

        - To view a specific category, append the url with its [/id](/api/categories/1/).
        """
        main_groups = Category.objects.filter(category_id__isnull=True)
        serializer = self.get_serializer(main_groups, many=True)

        return Response(serializer.data)

如果我去

http://127.0.0.1:8000/api/animals/

然后选择过滤器并在搜索字段中输入 el,然后过滤出其中包含字母 el 的动物:

[
    {
        "id": 15,
        "name": "Blauwgele Ara",
       
    },
    {
        "id": 71,
        "name": "Edelhert",

    {
        "id": 19,
        "name": "Edelpapegaai",
}]

或者我输入 ar:


 {
        "id": 15,
        "name": "Blauwgele Ara",
     
    },
    {
        "id": 24,
        "name": "Bobakmarmot",
}

我已经做了什么?当然,谷歌搜索了很多。观看 YouTube 剪辑。例如这个:

https://www.youtube.com/watch?v=i1PN_c5DmaI

但我没有看到阻止部分搜索单词的错误。

问题:如何实现部分搜索单词?

javascript reactjs django react-native react-native-paper
1个回答
0
投票

啊,好吧。我不知道。我也在学习。但我做了什么。在后端我改变了这个:

class AnimalViewSet(viewsets.ModelViewSet, permissions.BasePermission):

    queryset = Animal.objects.all().order_by('name')
    serializer_class = AnimalSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]

    filterset_fields = ['name']
    search_fields = ['name']

    def get_queryset(self):
        qs = Animal.objects.all()
        name = self.request.query_params.get('name')
        if name is not None:
            qs = qs.filter(name_icontains=name)
        return qs

在前端我改变了这个:

export const fetchAnimalData = async (text) => {
    const token = await retrieveToken();
    try {
        if (token) {
            const response = await fetch(`${API_URL}/api/animals/?search=${text}`, {
                method: "GET",
                headers: {
                    Authorization: `Token ${token}`,
                    Accept: "application/json",
                    "Content-Type": "application/json",
                },
            });
            return await response.json();
        } else {
            throw new Error(token);
        }
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

现在可以了。

© www.soinside.com 2019 - 2024. All rights reserved.