我实际上正在学习Javascript和React,但我有一个问题。我试图建立一个Pokedex,但我有一个问题。
我把一些无线电输入,使过滤器的代(口袋妖怪),但我不知道如何链接我的输入与apiGeneration数的API...
我还想按名称创建一个搜索栏,我可以在console.log()上看到searchBar.value,但我不能在searchBar元素上放置addeventlistener ...
非常感谢您的帮助。^^ API链接:https://pokebuildapi.fr/api/v1/pokemon
import axios from "axios";
import React, { useEffect, useState } from "react";
import Card from "./Card";
const Pokedex = () => {
const [data, setData] = useState([]);
const radios = ["1G", "2G", "3G", "4G", "5G", "6G", "7G", "8G"];
const [selectedRadio, setSelectedRadio] = useState("");
useEffect(() => {
axios
.get("https://pokebuildapi.fr/api/v1/pokemon")
.then((res) => setData(res.data));
}, []);
return (
<div className="pokemons">
<h2 id="search-title">Pokedex</h2>
<p className="search-text">Recherhe par nom</p>
<div>
<input type="search" id="search-bar"></input>
</div>
<div className="gen-search">
{radios.map((generation) => (
<ul className="radio-container">
<li>
<input
type="radio"
id={generation}
name="generationRadio"
checked={generation === selectedRadio}
onChange={(e) => setSelectedRadio(e.target.id)}
/>
<label htmlFor={generation}>{generation}</label>
</li>
</ul>
))}
</div>
{selectedRadio && (
<button onClick={() => setSelectedRadio("")}>
Annuler la recherche
</button>
)}
<div className="pokemon-container">
<ul>
{data
.filter((pokemon) => {
/* ... */
})
.map((pokemon, index) => (
<Card key={index} pokemon={pokemon} />
))}
</ul>
</div>
</div>
);
};
export default Pokedex;
API
// 20230130034321
// https://pokebuildapi.fr/api/v1/pokemon
[
{
"id": 1,
"pokedexId": 1,
"name": "Bulbizarre",
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
"slug": "Bulbizarre",
"stats": {
"HP": 45,
"attack": 49,
"defense": 49,
"special_attack": 65,
"special_defense": 65,
"speed": 45
},
"apiTypes": [
{
"name": "Poison",
"image": "https://static.wikia.nocookie.net/pokemongo/images/0/05/Poison.png"
},
{
"name": "Plante",
"image": "https://static.wikia.nocookie.net/pokemongo/images/c/c5/Grass.png"
}
],
"apiGeneration": 1,
1条答案
按热度按时间dl5txlt91#
下面是一个基于您的代码片段的示例。
变更:
useEffect
,以确保所选生成始终有效。filter()
,以将显示限制为选定代次。key
以使用pokemon.id
,这是一个更好的值,因为如果您在任何时间点重新排序或更改列表,它将需要做出React以做更少的工作。