【问题标题】:Can't load image from an API using React无法使用 React 从 API 加载图像
【发布时间】:2018-07-08 22:02:48
【问题描述】:

我成功地从 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;

如果我使用其他标签,如&lt;h1&gt;{props.img}&lt;/h1&gt;,它也会显示图像文件路径。我错过了什么我应该包括的东西吗?

【问题讨论】:

  • &lt;h1&gt;{props.img}&lt;/h1&gt;的情况下打印什么?
  • 'https://api.opendota.com/'+{props.img}
  • 图片路径一定是错误的。尝试传递完整的图片网址

标签: javascript html reactjs api


【解决方案1】:

img 的值不是您需要执行此操作的完整网址

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>

)

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多