无法使用React渲染HTML div?

时间:2018-12-10 20:09:24

标签: javascript reactjs

我正在尝试根据一个数组生成多个divs-但我无法这样做。我单击了一个按钮,该按钮应该通过映射返回divs,但它会返回任何内容。

class History extends Component {
  constructor(props) {
  super(props);
  this.state = {
    info: ""
  };
  this.generateDivs = this.generateDivs.bind(this);
}

async getCurrentHistory(address) {
  const info = await axios.get(`https://api3.tzscan.io/v2/bakings_history/${address}?number=10000`);
  return info.data[2];
}

async getHistory() {
  const info = await getCurrentHistory(
    "tz1hAYfexyzPGG6RhZZMpDvAHifubsbb6kgn"
  );
  this.setState({ info });
}

generateDivs() {
  const arr = this.state.info;
  const listItems = arr.map((cycles) => 
      <div class="box-1">
        Cycle: {cycles.cycle}
        Count: {cycles.count.count_all}
        Rewards: {cycles.reward}
      </div>
  );
  return (
    <div class="flex-container">
      { listItems }
    </div>
  )
}

componentWillMount() {
  this.getHistory();
}

render() {
  return (
    <div>
      <button onClick={this.generateDivs}>make divs</button>
    </div>
  );
}

1 个答案:

答案 0 :(得分:2)

您实际上并不是仅通过调用generateDivs函数来渲染div,它返回的JSX并没有在任何地方使用。

要使其正常工作,您可以执行以下操作-

render() {
  return (
    <div>
      <button onClick={this.showDivs}>make divs</button>
      {this.state.isDisplayed && this.generateDivs()}
    </div>
  );
}

其中showDivs是将状态属性isDisplayed切换为true的函数

主要要点是,在generateDivs函数中返回的JSX现在将在render函数中呈现出来。有很多切换显示的方法,这只是一种直接的方法