首页 > 解决方案 > 无法显示来自 pokeapi.co 的口袋妖怪图像

问题描述

我遇到了一个问题,我似乎无法在我的反应前端显示口袋妖怪图像,这是 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;

我还附上了前端的截图。在此处输入图像描述

标签: reactjspokeapi

解决方案


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

举个例子:

<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png" />


推荐阅读