javascript - 如何在React Native中过滤pokemon

标签 javascript reactjs database react-native user-interface

我试图在搜索栏组件中过滤掉神奇宝贝,但是当我在搜索栏中输入组件名称时,列表中没有任何反应。我一直在网上寻找解决方案,但其他示例太复杂,无法在我的代码中实现。我正在 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]

最佳答案

当用户想要搜索神奇宝贝时,您需要调用 updateSearch 函数。

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

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

现在更改您的updateSearch来处理搜索文本

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

同时将 SearchBarComponent 组件的 props 更改为(确保使用正确的名称)

<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()))
    });
}

希望这对您有帮助。如有疑问,请放心。

关于javascript - 如何在React Native中过滤pokemon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61530438/

相关文章:

javascript - 跨浏览器事件处理

javascript - 这是 Javascript 中有效的 monad 转换器吗?

javascript - 您将如何实现类似于 React Native 的条件导入?

node.js - 多次测试运行后的 Sequelizejs/未知关系 "xxx"

javascript - Facebook JS SDK : "(#100) No permission to publish the video" error

javascript - 如何使用 lxml 从文本区域获取 javascript 代码?

reactjs - 捕获 Material UI 弃用警告

javascript - 键盘更改所有组件在 native react 中的位置

mysql - 我应该在这个例子中使用外键吗?

mysql - 具有多个表的高级 MySQL 插入