我想做的是有条件地渲染对象中的一个元素,即如果chosenHour
键(在hoursInfo
数组中)等于19:30
,那么我想而不显示整个元素,所以我只有两个元素,而不是三个。
问题是如果不满足条件,IFE将返回null
,因此我仍然具有三个元素的对象,而第二个元素是null
。一切都在React中完成,所以我认为使用IFE以便在没有其他部分的情况下使用if语句是个好主意。
这是我的代码:
bookingObjToSend = {
name, email, phone, kidsNo, adultsNo, fullDate, year, month, day, chosenRoom,
hoursInfo: [
{ chosenHour:
chosenHour ==='9:30' ? '9:15' :
chosenHour ==='12:00' ? '12:15' :
chosenHour ==='14:30' ? '13:45' :
chosenHour ==='17:00' ? '16:45' :
chosenHour ==='19:30' ? '19:45' : null ,
renderedByBirthday: true, isBirthday: false },
(() => {
if(chosenHour !== '19:30'){ return { chosenHour:
chosenHour ==='9:30' ? '10:45' :
chosenHour ==='12:00' ? '13:45' :
chosenHour ==='14:30' ? '15:15' :
chosenHour ==='17:00' ? '18:15' :
null ,
renderedByBirthday: true, isBirthday: false}}
})(),
{ chosenHour, isBirthday: true}
]
}
答案 0 :(得分:1)
您可以使用filter
从数组中过滤掉所有虚假元素,以消除潜在的null
值。
bookingObjToSend = {
name, email, phone, kidsNo, adultsNo, fullDate, year, month, day, chosenRoom,
hoursInfo: [
{ chosenHour:
chosenHour ==='9:30' ? '9:15' :
chosenHour ==='12:00' ? '12:15' :
chosenHour ==='14:30' ? '13:45' :
chosenHour ==='17:00' ? '16:45' :
chosenHour ==='19:30' ? '19:45' : null ,
renderedByBirthday: true, isBirthday: false },
(() => {
if(chosenHour !== '19:30'){ return { chosenHour:
chosenHour ==='9:30' ? '10:45' :
chosenHour ==='12:00' ? '13:45' :
chosenHour ==='14:30' ? '15:15' :
chosenHour ==='17:00' ? '18:15' :
null ,
renderedByBirthday: true, isBirthday: false}}
})(),
{ chosenHour, isBirthday: true}
].filter(Boolean)
}