我正在尝试根据一个数组生成多个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>
);
}
答案 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
函数中呈现出来。有很多切换显示的方法,这只是一种直接的方法