【问题标题】:React Search Input Pokemon [closed]反应搜索输入口袋妖怪[关闭]
【发布时间】:2025-12-24 21:05:06
【问题描述】:

我想实现一个搜索栏,只要用户输入它,它就会过滤掉一个神奇宝贝列表。我已经查看了其他解决方案,但我仍然感到困惑。这是我的代码:

import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import Loading from "../layout/Loading";
import axios from "axios";

export default class PokemonList extends Component {
  state = {
    url: "https://pokeapi.co/api/v2/pokemon?/",
    pokemon: null,
    pokeTemp: null,
    searchValue: "",
  };

  //information about pokemon
  async componentDidMount() {
    const res = await axios.get(this.state.url);
    this.setState({ pokemon: res.data["results"] });
    this.setState({ pokeTemp: res.data["results"] });
  }

  //user search for pokemon
  handleInputChange = (event) => {
    const value = event.target.value;
    this.setState({ searchValue: value });
  };

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

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.searchValue}
          onChange={this.handleInputChange}
        />
        {this.state.pokemon ? (
          <div className="row">
            {this.state.pokemon.map((pokemon) => (
              <PokemonCard
                key={pokemon.name}
                name={pokemon.name}
                url={pokemon.url}
              />
            ))}
          </div>
        ) : (
          <Loading />
        )}
      </div>
    );
  }
}

我有一个想法,一旦用户输入一个值,它就会更新该值,然后我们还使用该值来过滤数据,然后稍后在 div 中映射该过滤器,但我在实现时遇到了一些麻烦这个。

谁能解释我做错了什么? 任何帮助或解释都会有所帮助,谢谢!

【问题讨论】:

    标签: javascript reactjs search input filter


    【解决方案1】:

    您的代码实际上运行良好,只是您忘记在handleInputChange 中调用filterPokemon()

    https://codesandbox.io/s/recursing-bhaskara-n6gi0?file=/src/App.js

    【讨论】: