ReactJs:如何在render方法中使用map函数处理空数组

问题描述 投票:2回答:4

我试图用一些JSON数据打印表,但是当我使用map方法时,我无法渲染空数组。

JSON数据:

    [{
	"id": 6,
	"firstname": "Sharon",
	"lastname": "Jenkins",
	"specialties": []
}, {
	"id": 2,
	"firstname": "Helen",
	"lastname": "Leary",
	"specialties": [{
		"id": 1,
		"name": "radiology"
	}]
}, {
	"id": 4,
	"firstname": "Rafael",
	"lastname": "Ortega",
	"specialties": [{
		"id": 2,
		"name": "surgery"
	}]
}, {
	"id": 5,
	"firstname": "Henry",
	"lastname": "Stevens",
	"specialties": [{
		"id": 1,
		"name": "radiology"
	}]
}]

我的代码:

 {this.state.vets.map(vet =><tr><td>{vet.firstname}</td>
                  {  
                                  
                  vet.specialties.map((subitem,i) => {
                       
                    return <td>{subitem.name}</td> })}<td>EDIT</td><td id={vet.firstname}><div class="funkyradio">

现在我收到以下错误enter image description here

由于Sharon没有专家,我需要打印为N / A.

如何查看专业是空的并打印N / A.

javascript reactjs html5
4个回答
1
投票

尝试始终渲染TD标记,如:

{
  this.state.vets.map(vet =>
    <tr>
      <td>{vet.firstname}</td>
        <td>                
          {vet.specialties.map((subitem,i) => {
            return <span>{subitem.name}</span>
          })}
        </td>
        <td>EDIT</td>
        <td id={vet.firstname}>
          <div class="funkyradio">

1
投票

<table>
        {dataJSON.map(({ id, firstname, lastname, specialties }) => {
          return (
            <tr>
              <td> {`${firstname} ${lastname}`} </td>
              <td> {specialties.map(specialty => specialty.name).join(",")} </td>
              <td> <span> EDIT </span> </td>
            </tr>
          );
        })}
</table>

0
投票

像这样使用条件语句

{ this.state.vets.length > 0 
 ? this.state.vets.map(()=>Your logic)
 : <Your custom message/>
}

0
投票

主要是为了可读性,而不是使用object属性,我会创建一个单独的函数,如果有的话,将返回专业,否则N / A

© www.soinside.com 2019 - 2024. All rights reserved.