使用数组索引反应渲染数据

时间:2020-05-08 05:03:30

标签: javascript reactjs fetch

我在React js中遇到了一个问题,我想从rest API渲染所有数据并用数字索引显示。

其他API:

[
{
"id": "1",
"start_date": "2020-05-08 09:45:00",
"end_date": "2020-05-08 10:00:00",
"full_name": "mirza",
"cust_full_name": "furqan",
},
{
"id": "2",
"start_date": "2020-05-08 02:45:00",
"end_date": "2020-05-08 03:00:00",
"full_name": "mirza",
"cust_full_name": "ahmed",
},
{
"id": "3",
"start_date": "2020-05-08 06:45:00",
"end_date": "2020-05-08 07:00:00",
"full_name": "mirza",
"cust_full_name": "ali",
}
]

我的代码:

render() 
{ 

  let FullNameSlot1 = null   //FullNameSlot
  let SecondFullNameSlot1 = null

  let BaberNameSlot1 = null    //BaberNameSlot
  let SecondBaberNameSlot1 = null    


  if (this.state.appointmentdata && this.state.appointmentdata.length
    this.state.appointmentdata[0].start_date.toString() > this.state.newprevious   
    )
    {
    FullNameSlot1 = (
          <p key={0}>{this.state.appointmentdata[0].cust_full_name}</p>
        )

      BaberNameSlot1 = (
        <p key={0}>{this.state.appointmentdata[0].full_name}</p>
      )
 }

我想使用数组{index}

渲染数据

if (this.state.appointmentdata && this.state.appointmentdata.length
  this.state.appointmentdata[1].start_date.toString() > this.state.newprevious   
  )

  {
    SecondFullNameSlot1 = (
      <p key={1}>{this.state.appointmentdata[1].cust_full_name}</p>
    )
    SecondBaberNameSlot1 = (
      <p key={1}>{this.state.appointmentdata[1].full_name}</p>
    )
}


我想渲染其余API的所有数据并显示一个数字索引。将我的代码设置为simple

 <p key={index}>{this.state.appointmentdata[index][0].cust_full_name}</p>
 <p key={index}>{this.state.appointmentdata[index][1].cust_full_name}</p>

演示:

https://codesandbox.io/s/agitated-elion-quqp1

我该怎么办?有人帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用条件渲染,而最终条件是三进制,可以将数据数组映射到JSX或返回null。 array :: map第一个参数是要迭代的当前元素,第二个参数是当前索引。当像这样返回JSX时,尽管您需要返回一个节点。在这里,我使用了一个react Fragment并在其中附加了密钥。我还破坏了要显示的元素属性。

Conditional Rendering Lists and Keys

{
  (this.state.appointmentdata && 
  this.state.appointmentdata.length &&
  this.state.appointmentdata[1].start_date.toString() > this.state.newprevious)
  ? this.state.appointmentdata.map(({ cust_full_name, full_name }, index) => (
    <Fragment key={index}>
      <p>{cust_full_name}</p>
      <p>{full_name}</p>
    </Fragment>
  ) : null
}

答案 1 :(得分:0)

@adnan khan欢迎使用Stackoverflow!渲染元素数组,您可以使用Array.map函数https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

在您的示例中,它可能看起来像这样

if(this.state.appointmentdata && this.state.appointmentdata.length){
this.state.appointmentdata.map((data ,index) => <p key={index}>{data.cust_full_name}</p> )

}