簡體   English   中英

無法使用React從API加載圖像

[英]Can't load image from an API using React

我成功地從OpenDota API加載了數據,但是以某種方式,當我在Heroes.js中傳遞圖像道具時,圖像損壞了

這是我加載API的組件。

HeroStats.js

import React, { Component } from 'react'
import Sidebar from "./Sidebar";
import Heroes from "./Heroes"
import "./App.css"
import axios from "axios";

const URL = "https://api.opendota.com/api/heroStats";

class HeroStats extends Component {
    state = {
        data: []
    }

    componentDidMount() {
        axios.get(URL)
            .then(res => {
                this.setState({
                    data: res.data
                });
            });
    }

    render() {
        const Stats = this.state.data.map(stat => (
            <Heroes
                key={stat.id}
                id={stat.id}
                name={stat.name}
                localized_name={stat.localized_name}
                img={stat.img}
                icon={stat.icon}
                pro_win={stat.pro_win}
                pro_pick={stat.pro_pick}
                pro_ban={stat.pro_ban}

            />
        ))
        return (
            <div>
                {Stats}
            </div>
        )
    }
}

export default HeroStats;

在這里我傳遞道具 Heroes.js

import React from 'react'

const Heroes = (props) => (
    <div>

        <h1>{props.localized_name}</h1>
        <img src={props.img} />
        <img src={props.icon} />
        <h1>{props.pro_win}</h1>
        <h1>{props.pro_pick}</h1>
        <h1>{props.pro_ban}</h1>
    </div>

)

export default Heroes;

同樣,如果我使用其他標簽,例如<h1>{props.img}</h1>它會顯示圖像文件路徑。 我錯過了我應該包括的東西嗎?

img的值不是您需要執行的完整URL

const Heroes = (props) => (
    <div>

        <h1>{props.localized_name}</h1>
        <img src={"https://api.opendota.com" + props.img} />
        <img src={"https://api.opendota.com" + props.icon} />
        <h1>{props.pro_win}</h1>
        <h1>{props.pro_pick}</h1>
        <h1>{props.pro_ban}</h1>
    </div>

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM