简体   繁体   中英

Combine multiple React components

How do I display multiple components on my page currently refundTimeLine shows [Object object] .

Code:

let tdWidth = "25%"
let refundTimeLine = "";
transactionJourney.map((trans) => {
    if(trans.key=="refund") {
        trans.value.forEach((refundRow) => {
            console.log(refundRow);
            refundTimeLine+= <TimelineStatus tdWidth={tdWidth} statusObj={{date: refundRow.date, time: refundRow.time}} statusClass={statusIcon} tickClass={tickClass} text={"Refund of "+refundRow.amount} />
        })
    }
})

console.log(refundTimeLine);
return (
    <tr>
        <TimelineStatus tdWidth={tdWidth} statusObj={_this.getStatusObject('paymentInitiated')} statusClass={statusIcon} tickClass={tickClass} text={"Payment Initiated"} />
        <TimelineStatus tdWidth={tdWidth} statusObj={_this.getStatusObject('paymentSuccessful')} statusClass={statusIcon} tickClass={tickClass} text={"Payment Succesful"} />
        <TimelineStatus tdWidth={tdWidth} statusObj={_this.getStatusObject('settlementInProgress')} statusClass={statusIcon} tickClass={tickClass} text={"Settlement in Progress"} />
        <TimelineStatus tdWidth={tdWidth} statusClass={statusIconDisabled} tickClass={tickClass} text={[_this.props.transactionData.paymentBreakUp.amountSettled+" will be",<br/>,  "credited to your bank",<br/>,"account in 72 hours"]} />
        {refundTimeLine}
    </tr>
)

Please help new to React

Reason is , you initially defined refundTimeLine as string and then appending the react component by using += . Instead of that define refundTimeLine as an array and push the react component inside that.

Write it like this:

let refundTimeLine = [];
transactionJourney.map( (trans, i) => {
   if(trans.key=="refund") {

      trans.value.forEach((refundRow, j) => {
          refundTimeLine.push(<TimelineStatus
                                  key={i + '_' + j}   //add a unique key 
                                  tdWidth={tdWidth} 
                                  statusObj={{date: refundRow.date, time: refundRow.time}} 
                                  statusClass={statusIcon} 
                                  tickClass={tickClass} 
                                  text={"Refund of "+refundRow.amount} 
                              />)
      })

   }
})

Suggestion :

1- You are using map here, instead of that use forEach .

2- Don't forgot to assign the unique key to each ui element created inside loop , it will help React to identified the item that changed, if any change happens, it will improve the performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM