【问题标题】:Unable to render html divs with React?无法使用 React 呈现 html div?
【发布时间】:2019-05-11 18:43:23
【问题描述】:

我正在尝试基于一个数组生成几个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>
  );
}

【问题讨论】:

  • @andymccullough 我没有将我的componentWillMount 包含在用数组填充 state.info 的这段代码中
  • 你能补充一下吗
  • @andymccullough 更新
  • 您是重新输入此代码还是复制/粘贴它?您是否在 array.map() 函数调用中缺少右括号 )

标签: javascript reactjs


【解决方案1】:

您实际上并没有通过调用 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 函数中呈现出来。切换显示的方法有很多,这只是一种直接的方式

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 2015-08-04
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多