![](/img/trans.png)
[英]I'm trying to append an image from a javascript object Array onto my html page
[英]I'm trying to access an image that is in an object inside of an array
我做了這個按鈕,隨機選擇一個聯賽冠軍並顯示名字。 現在,我試圖顯示與冠軍一同出現的圖像。 我已經對JSON進行了一些操作,以使用Object.values獲取一些數據以獲取要顯示的名稱。 如果使用.map(),則將獲得所有圖像,直到單擊按鈕,然后僅顯示生成的名稱和圖像。 在單擊按鈕之前,我希望它是空白的。 謝謝。
class App extends Component {
state = {
randomChampion: [],
runes: [],
spells: [],
items: []
}
async componentDidMount() {
try {
const res = await fetch('http://ddragon.leagueoflegends.com/cdn/7.24.2/data/en_US/champion.json');
const champions = await res.json();
console.log(champions);
this.setState({
randomChampion: Object.values(champions.data),
});
} catch(e) {
console.log(e);
}
}
getChampion = () => {
this.setState({
randomChampion: this.state.champions[Math.floor(Math.random() * this.state.champions.length)],
})
};
render() {
console.log(Object.values(this.state.randomChampion));
const CHAMPION_SQUARE = 'http://ddragon.leagueoflegends.com/cdn/7.24.2/img/champion/';
// const endImageURL = Object.values(this.state.randomChampion.image.full);
// console.log(this.state.champions);
return (
<div>
<HeadsUp>
<h1>ULTIMATE BRAVERY</h1>
<p>Are you brave enough?</p>
</HeadsUp>
<button onClick={this.getChampion}>
Please Not Teemo
</button>
<ChampGrid>
{this.state.randomChampion.name}
{/* <img src={`${CHAMPION_SQUARE}${endImageURL}`}/> */}
</ChampGrid>
使用您的方法,您將需要2種不同的狀態來存儲冠軍數據:
champions
狀態:存儲您從json獲得的所有冠軍數據 randomChampion
狀態:存儲隨機選擇的冠軍對象 因此,您首先需要初始化這兩個狀態:
state = {
champions: [],
randomChampion: {}
}
在你componentDidMount
,使得API調用后,你SETSTATE到champions
的狀態,不randomChampion
:
// ... fetch data ...
this.setState({
champions: Object.values(champions.data),
})
現在您的getChampion()
函數就有意義了,它只需選擇一個隨機冠軍並將其設置為randomChampion
。
最后,您就像這樣渲染它們:
render() {
return (
<div>
<HeadsUp>
<h1>ULTIMATE BRAVERY</h1>
<p>Are you brave enough?</p>
</HeadsUp>
<button onClick={this.getChampion}>Please Not Teemo</button>
<ChampGrid>
{this.state.randomChampion.image
? <img src={`http://ddragon.leagueoflegends.com/cdn/7.24.2/img/champion/${this.state.randomChampion.image.full}`} />
: null}
{this.state.randomChampion.name}
</ChampGrid>
</div>
)
}
圖片網址如下所示: http://ddragon.leagueoflegends.com/cdn/7.24.2/img/champion/<champion-image-name>
: http://ddragon.leagueoflegends.com/cdn/7.24.2/img/champion/<champion-image-name>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.