首页 > 解决方案 > Pokedex 项目 api 反应 js

问题描述

我正在尝试学习,对我们做出反应并尝试在我的 pokedex 应用程序上加载 API。https://pokeapi.co/api/v2/pokedex/1/我正在尝试加载( pokemon_entries )列表中的每个口袋妖怪,但我不知道该怎么做

我已经创建了不同口袋妖怪的卡片,并尝试在我的应用程序上加载列表

列出口袋妖怪

import React from 'react';
import Loader from '../components/Loader';



class ListPokemon extends React.Component {
    state = {
        isLoading: false,
        data: [ ]

      };

    async componentDidMount() {
        this.setState({isLoading:true})
        const {name, url} = this.props;

        try {
            const response = await fetch(`https://pokeapi.co/api/v2/pokedex/1/`);
            const json = await response.json();
            this.setState({data: json,isLoading:false})
            console.log({json})
          } catch (err){
            console.log(err.msg);
            this.setState({isLoading:false})
            throw err
        }
    }



    render() {
        const {isLoading,data} = this.state;
        return (
          <>
            <h1>Lorem</h1>
          {
            isLoading ?<Loader/> : <h1>{data.entry_number}</h1>
          }


          </>
        );
      }
    }


export default ListPokemon

数据口袋妖怪:

import React from 'react';
import { Card,Container,Row,Col } from 'react-bootstrap';

const DataPokemon = props =>  {const { name } = props;


return(
    <Container>
  <Row>
  <Col xs={6}>
    <Card style={{ width: '18rem' }}>
  <Card.Img variant="top" src="holder.js/100px180" />
  <Card.Body>
    <Card.Title>{name}</Card.Title>
    <Card.Text>

    </Card.Text>
    {/* <Button variant="primary">Go somewhere</Button> */}
  </Card.Body>
</Card>
</Col>
</Row>
</Container>
)
}





export default DataPokemon;

谢谢 !

标签: javascriptreactjsapi

解决方案


您可以更改 x 并获得更多或更少的口袋妖怪。

     const pokeArray = [];   

     for(let i=1; i<x; i++) {
              axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`).then(res => {
                pokeArray.push( {
                  id: i,
                  name: res.data.name,
                  photo: res.data['sprites']['front_default'],
                  hp: res.data['stats'][5]['base_stat'],
                  attack: res.data['stats'][4]['base_stat'],
                  defense : res.data['stats'][3]['base_stat'],
                } )
              })
            }

推荐阅读