【问题标题】:Unable to display pokemon image from pokeapi.co无法显示来自 pokeapi.co 的口袋妖怪图像
【发布时间】:2021-09-19 00:49:02
【问题描述】:

我遇到了一个问题,我似乎无法在我的 react 前端显示 pokemon 图像,这是 api:https://pokeapi.co/

import React, { Component } from 'react';

class Card extends Component {
    state = {
        name: "",
        imageUrl: "",
        pokemonIndex: "",
    }
    componentDidMount() {
        const {name, url} = this.props;
        const pokemonIndex = url.split('/')[url.split('/').length - 2];
        const imageUrl = `http://pokeapi.co/media/sprites/pokemon/${pokemonIndex}.png`
        this.setState({name, imageUrl, pokemonIndex})
    }
    render() {
        
       
        
        return (
            <div className="card" >
                <img src= {this.state.imageUrl}/>
                <h3> {this.state.name} </h3>
                
            </div>
        );
    }
}

export default Card;

我还附上前端截图

【问题讨论】:

标签: reactjs pokeapi


【解决方案1】:

查看 API 中的文档和 JSON 文件,我想我发现了您的问题。您使用了错误的 img 链接。正确的格式是:https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png

例如:

&lt;img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png" /&gt;

【讨论】:

  • 你在哪里找到这个链接?我在文档的任何地方都找不到它。
  • @RMP1992 我打开了 json 文件并搜索了 png,然后我测试了链接以找到正确的链接
【解决方案2】:

对于 pokeapi,正确的 URI 格式如下。

https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/imageName.png

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案3】:

@erick-silva 回答不完整且容易出错。

获取特定口袋妖怪图像的正确方法是:

  1. 从 PokeAPI 获取该口袋妖怪的信息,例如 bulbasaur。 -> GET https://pokeapi.co/api/v2/pokemon/bulbasaur
  2. 解析返回的 JSON 属性 .sprites,选择我们想要使用的版本和精灵的种类,比如 Pokemon Crystal front.sprites.versions["generation-ii"].crystal.front_default
  3. 使用提供的链接并加载图像:https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-ii/crystal/1.png

使用此方法将确保您始终获取正确的图像,以防ids 更改或图像名称不是口袋妖怪的id

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多