Javascript 如何在jsx中呈现字符串<;部门>;在对象数组上使用reduce

Javascript 如何在jsx中呈现字符串<;部门>;在对象数组上使用reduce,javascript,arrays,reactjs,frontend,jsx,Javascript,Arrays,Reactjs,Frontend,Jsx,我想呈现航班停靠站位置代码列表。我有一个停靠站对象数组: flight = { departStops:1, departSegments:{ { departure: {iataCode: "TXL"}, arrival: {iataCode: "FRA"} }, { departure: {iataCode: "FRA"}, arrival: {iataCode: "YUL"} } } 在返回之前的组件函数中,我创建了字符串常量: const

我想呈现航班停靠站位置代码列表。我有一个停靠站对象数组:

flight = {
departStops:1,
departSegments:{
 {
    departure: {iataCode: "TXL"},
    arrival: {iataCode: "FRA"}
   },
 {
    departure: {iataCode: "FRA"},
    arrival: {iataCode: "YUL"}
   }
}
在返回之前的组件函数中,我创建了字符串常量:

const myString = flight.departSegments.reduce((acc,item) => {
                        if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
                            if (acc.length > 0) {
                                acc.concat(',',item.arrival.iataCode)
                            } else {
                                acc.concat(item.arrival.iataCode)
                            }
                        }
                        return acc
                    },"")
这就是我在组件中呈现字符串的方式:

<div>
    {
        flight.departStops > 0 
        ?
        myString
        : 
        null
    }
</div>

{
航班起飞时间>0
?
myString
: 
无效的
}

问题是myString在呈现时仍然是空字符串

字符串在javascript中是不可变的,为了使其工作,您需要返回acc.concat()结果

附言

您可以简化渲染

<div> { (flight.departStops > 0) && myString } </div> 
{(flight.departStops>0)和&myString}

字符串在javascript中是不可变的,为了使其正常工作,您需要返回acc.concat()结果

附言

您可以简化渲染

<div> { (flight.departStops > 0) && myString } </div> 
{(flight.departStops>0)和&myString}

您需要像这样从reduce返回

if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
    if (acc.length > 0) {
         return acc.concat(',',item.arrival.iataCode)
    } else {
         return acc.concat(item.arrival.iataCode)
    }
  }

此外,构建片段的方式也很糟糕。它应该是数组,而不是对象。

您需要像这样从reduce返回

if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
    if (acc.length > 0) {
         return acc.concat(',',item.arrival.iataCode)
    } else {
         return acc.concat(item.arrival.iataCode)
    }
  }
此外,构建片段的方式也很糟糕。它应该是数组,而不是对象