React 如何调用 API 并在对象数组中显示数组 PokeAPI

React how to make a call to an API and display an array in an array of objects PokeAPI

我正在从事的项目需要帮助,我希望能够显示我输入的神奇宝贝的动作,我可以 console.log 一个对象数组,其中包含较小的数组想抓取并展示,我该怎么做?我尝试了方法 getPokemonNames 的集群,该方法应该获取口袋妖怪动作的名称,但这是我无法再想的地方。

import React, {useState} from 'react';
import PokemonName from './PokemonName';
import axios from 'axios';


function App() {
  const [pokemon, setPokemon] = useState([])
  const [loading, setLoading] = useState(false)
  const [moves, setMoves] = useState([])
  
  const getPokemon = async (name) =>{
    setLoading(true);
    const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${name}`)
    const data = response.data;
    setPokemon(data);
    setMoves(data.moves);
    setLoading(false);
    console.log(data)
    getPokemonNames(data.moves)
    
   // const pokemonMovesAmount = pokemon.moves.map
  }
  const getPokemonNames = (data) =>{
    console.log(data);
    data.move.name.map((moves, key)=>(
      <div key={key}>
        <span>{moves.moves.name}</span>
      </div>
    ))
    
  }
  
  return (
    <>
    <PokemonName getPokemon={getPokemon}/>
    <div>
      {!loading && pokemon ? (<div> 
      </div>): null}
      <img src={pokemon.sprites?.front_default}/>
      <div className="container">
        {getPokemonNames}
      </div>
    </div>
    </>
  );
}

export default App;

这是宠物小精灵名称组成部分

import React, {useState} from 'react'
const onSubmit =(e) =>{
    e.preventDefault();
}
export default function PokemonName(props) {
    const [search, setSearch] = useState('');
   
    return (
        
        <div>
            <div> 
                <h1>{search}</h1>
                <form onSubmit={onSubmit}>
                <input onChange={e => setSearch(e.target.value)} type ="text" placeholder="Search for Pokemon"></input>
                <button onClick={(e) => props.getPokemon(search)}>Search</button>
                </form >
            </div>
        </div>
    )
}

编辑,这显示了更多关于我在搜索 pokemon mew 后得到的数据

您的 getPokemonNames 有误。您正在尝试执行 data.move.name.map 这意味着您正在从“数据”内部映射“移动”。您需要映射“移动”数组。以下是您的操作方法。

const getPokemonNames = (data) =>{
    data.moves.map(item, key)=>(
      <div key={key}>
        <span>{item.move.name}</span>
      </div>
    ))
}

第一步,确保传递参数数据

const [moves, setMoves] = useState([])
// since you set setMoves to be data.moves second step you can iterate over data only
return (
<>
<PokemonName getPokemon={getPokemon}/>
<div>
  {!loading && pokemon ? (<div> 
  </div>): null}
  <img src={pokemon.sprites?.front_default}/>
  <div className="container">
    {getPokemonNames(moves)}
  </div>
</div>
</>
);

第二步,调整你的 getPokemon 方法

const getPokemonNames = (data) => {
return data.map(moveD, key)=>(
  <div key={key}>
    <span>{moveD.move.name}</span>
  </div>
))
}