首页 > 解决方案 > 反应渲染中的嵌套返回html

问题描述

所以我会试着解释一下这里的情况。

概述:我收到了一系列交易。然后我根据月份对这些交易进行分组。对象中每个项目的键groupedTransactions是一个月,如 [02-2012] 等,键的值是包含该月所有交易的对象数组。现在我想要的是,在里面的渲染方法中,<tbody>我调用一个函数,该函数将返回:表中的一行显示“3 月份的交易”,然后是所有发生的交易。

到目前为止的代码:在渲染或返回功能组件时,我应该说:

      <tbody>
         <tr>
           <th>Some heading</th>
         </tr>

        {!isLoading?

        accountSummary(account.transactions,account.balances.current )
        :''
      }
 </tbody>

现在在 accountSummary 方法中:

 const accountSummary = (accTx,currentBalance)=>{
        console.log('called account summary');
        let groupedTransactions = groupTransactionsByMonth(accTx);

        return Object.keys(groupedTransactions).map((month,index)=>{
                console.log('called for loop');
                console.log(month);
                return(

                        <tr>
                            <td style={{fontWeight:'bold',fontSize:'1em'}}>Transactions in the Month of {moment(month).format("MMMM")}</td>
                            {loopOverGroupedTxByMonth(month,groupedTransactions)}
                        </tr>

                )

        })
    };

最后在loopOverGroupedTxByMonth(month,groupedTransactions)方法中:

    const loopOverGroupedTxByMonth = (month,groupedTransactions) =>{
       return  groupedTransactions[month].forEach(function (transaction, index) {
            console.log(transaction)
            //Lot of variables here that are used below so no need for that 
            return (
                <tr>
                    <td><Moment format="LL">{transaction.date}</Moment></td>
                    <td>{transaction.original_description}</td>
                    <td>{displayInflow ? displayInflow : '---'}</td>
                    <td>{displayOutflow ? displayOutflow : '---'}</td>

                </tr>
            );
        });
    }

因此,您现在可以猜到,accountSummary 方法确实返回“3 月份的交易”和 april BUTT,它没有返回该loopOverTxByMonth方法应该返回的任何东西。有趣的是,在控制台中一切都很好。我得到一个月,然后是所有交易,然后是一个月,依此类推。所以我在这里做错了什么,我知道它有点复杂,但请耐心等待。谢谢,如果您需要进一步的清晰度或代码,我可以回答任何问题。

标签: javascriptreactjs

解决方案


const loopOverGroupedTxByMonth = (month,groupedTransactions) =>{
       return  groupedTransactions[month].map(function (transaction, index) {
            console.log(transaction)
            //Lot of variables here that are used below so no need for that 
            return (
                <tr>
                    <td><Moment format="LL">{transaction.date}</Moment></td>
                    <td>{transaction.original_description}</td>
                    <td>{displayInflow ? displayInflow : '---'}</td>
                    <td>{displayOutflow ? displayOutflow : '---'}</td>

                </tr>
            );
        });
    }

替换forEachmap并查看魔术。


推荐阅读