javascript - ReactJs:如何在渲染方法中使用映射函数处理空数组

标签 javascript reactjs html

我正在尝试使用一些 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。

最佳答案

尝试始终渲染 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">

关于javascript - ReactJs:如何在渲染方法中使用映射函数处理空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880594/

相关文章:

javascript - innerHTML 中的字符数

javascript - 在 AngularJS 中异步加载数据的正确方法

javascript - goodreads API 给出了 Cross-Origin Request Blocked : error in javascript

javascript - 异步代码运行 - 在react-native中使用Javascript OOP

javascript - 如何增加按钮单击Reactjs上的项目?

javascript - 选中复选框时显示/隐藏其余行

html - 如何强制div的内容显示在移动设备背景图片的下方?

javascript - ng-型号 : empty strings should be null

reactjs - Redux Form 异步验证无限递归

javascript - 在网站底部放置一个横幅,将所有元素向上推