如何使用 JSX 重复一个数组 n 次

How to repeat an array n times using JSX

我正在我的应用程序中使用 React/JSX。

我需要在第一次中重复API的数据n次。如果我点击按钮,它会重复 n 次。又一次点击-> 再重复 n 次,一遍又一遍。 api 每次都给我 1 个结果。如果需要我可以定义结果

我的代码:

 const n=2;

 arr:[];


handleClick(){
//i need the code to increase n another 2 times
}



//the array here without the code to fill api data. not relevant
 this.state.arr.map((d,key)=>
<span>age: {d.age} </span>


<button onClick={this.handleClick} >

第一个结果中的预期结果:

年龄:20

年龄:24

点击按钮后:

年龄:20

年龄:24

年龄:48

年龄:19

取决于您的 API 调用位置,但为了更新数组,您应该在 handleClick

中使用 this.setState
handleClick() {
  this.setState({
    arr: this.state.arr.concat(newContentArray)
  })
}

不知道你是如何获取数据的,但这是一般原则。将现有的 this.state.arrconcat 数组与新数据一起使用。

请务必在 button 事件处理程序上使用 bind 或箭头函数。