我试图访问数组内对象中的图像

时间:2017-12-28 04:29:45

标签: javascript arrays reactjs object

我做了这个按钮,随机选择一个联盟冠军并显示名称。现在我试图显示与冠军一起出现的图像。我已经对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>

1 个答案:

答案 0 :(得分:1)

使用您的方法,您需要2种不同的状态来存储冠军数据:

  1. champions州:存储您从json
  2. 获得的所有冠军数据
  3. randomChampion州:存储随机选择的冠军对象
  4. 因此,您首先需要初始化这两种状态:

    state = {
      champions: [],
      randomChampion: {}
    }
    

    componentDidMount中,在进行API调用后,您将州设置为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>