首页 > 解决方案 > 如何在反应原生中过滤口袋妖怪

问题描述

我试图在我的搜索栏组件中过滤掉口袋妖怪,但是当我在搜索栏中输入组件的名称时,列表没有任何反应。我一直在网上搜索解决方案,但其他示例太复杂而无法在我的代码中实现。我正在 consoling.log 来自搜索栏组件的输入并记录输入文本。但只是不知道如何过滤掉口袋妖怪。如果有人可以帮助我,我将非常感激!

// Home.js(Where pokemon ifo is coming from in the componentDidiMount abd then I pass down a function to the searchbar component)

import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: [],
            filteredPokemon:[]
        }
    }

    componentDidMount() {
        fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
            .then((res)=> res.json())
            .then((response)=> {
                this.setState({
                    isLoading: false,
                    dataSource: response.results,
                })
                console.log("RESPONSE",response)
                console.log("RESPONSE.RESSSULTS",response.results)
            })

    }

    filterPokemon =(textToSearch)=> {
        const allPokemon = [...this.state.dataSource];
        this.setState({
            dataSource: allPokemon.filter(pokemon=> pokemon.name.toLowerCase().includes(textToSearch.toLowerCase()))
        });

        console.log("TextToSearch",textToSearch)
    }

    render() {

        const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
        return(
            <View style={GlobalStyles.container}>
                <SearchBarComponent filterPoke={this.filteredPokemon} style={GlobalStyles.searchBar}/>
                <PokeBanner/>
                <View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
                <View style={GlobalStyles.pokeFlatList}>
                <FlatList
                    contentContainerStyle={{paddingBottom: 70}}
                    keyExtractor={(item, index) => item.name}
                    numColumns={3}
                    data={this.state.dataSource} 
                    renderItem={({item})=> 
                    <View style={{flex: 1,justifyContent:"center", alignItems:"center", flexDirection: "row", marginBottom: 50, padding: 10}}>
                    <TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails', 
                    {item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
                        <PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
                    </TouchableOpacity>
                    </View>
                    }/>
                </View>
            </View>
        )
    }
}


export default Home;





// SearchBarComponent(Where I take the function passed down as a prop and use it in the updateSearch method)

import React from "react";
import {View, StyleSheet } from "react-native";
import { SearchBar } from 'react-native-elements';
import { GlobalStyles } from "../styles/GlobalStyles";


class SearchBarComponent extends React.Component {
  state = {
    search: '',
  };

updateSearch=()=> {
  this.props.pokeFilter(this.state.search);
  console.log(this.state.search)
}



  render() {
    const { search } = this.state;
    console.log(search)
    return (
        <View style={GlobalStyles.searchBar}>
            <SearchBar
                placeholder="Search pokemon..."
                onChangeText={text=>this.setState({search: text})} 
                value={search}
            />
        </View>

    );
  }
}


export default SearchBarComponent;




[![enter image description here][1]][1]

标签: javascriptreactjsdatabasereact-nativeuser-interface

解决方案


updateSearch当用户想要搜索口袋妖怪时,您需要调用您的函数。

有多种方法可以做到这一点,例如您可以保留一个单独的按钮来处理提交功能或在搜索栏组件updateSearch内部调用,如下所示,onChangeText

<SearchBar
    placeholder="Search pokemon..."
    onChangeText={this.updateSearch}
    value={search}
/>

现在改变你updateSearch来处理搜索文本

updateSearch = (text) => {
  this.setState({ search: text });
  this.props.pokeFilter(this.state.search);
}

还将组件的道具更改SearchBarComponent为(确保使用正确的名称

<SearchBarComponent pokeFilter={this.filterPokemon} style={GlobalStyles.searchBar}/>

但是你必须保留一个临时变量来存储你所有的口袋妖怪。因为当用户修改搜索字段时,您需要从所有口袋妖怪中过滤数据。

componentDidMount() {
    fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
        .then((res) => res.json())
        .then((response) => {
            this.setState({
                isLoading: false,
                // keep a temp to store all pokemons
                pokemons: response.results,
                dataSource: response.results,
            });
        });
}

现在您可以使用您的过滤功能

filterPokemon = (textToSearch) => {
    // load all pokemons from temp
    const allPokemon = [...this.state.pokemons];
    this.setState({
        dataSource: allPokemon.filter(pokemon => pokemon.name.toLowerCase().includes(textToSearch.toLowerCase()))
    });
}

希望这可以帮助你。随意怀疑。


推荐阅读