【发布时间】:2021-04-14 21:31:40
【问题描述】:
我在一个数组中有两个团队,它们有 id 1 和 2:
{
"teams": [
{
"id": 1,
"name": "England",
"groupName": 4
},
{
"id": 2,
"name": "Germany",
"groupName": 6
}
]
}
我必须对后端进行 API 调用,该调用有时会返回 0 的 id(未映射到上面的数组中)。这是我尝试将其呈现为 Table 时的 JSX 代码:
<td style={{ width: '16.66%', wordBreak: 'break-all' }}>
{teams.find((team) => team.id === fixture.team1Id).name}
</td>
结果,当fixture.team1Id 为0 时,我得到TypeError: Cannot read property 'name' of undefined。如何在前端处理它以在fixture.team1Id 为0 时返回类似“TBC”的字符串?
【问题讨论】:
-
{(teams.find((team) => team.id === fixture.team1Id) | {}).name} -
{(teams.find((team) => team.id === fixture.team1Id)? (teams.find((team) => team.id === fixture.team1Id) .name || "TBC" } 希望这个 sn-p 有帮助,你可以简化它以使其更干净
标签: javascript reactjs jsx react-bootstrap