javascript - 反应渲染中的嵌套返回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
方法应该返回的任何东西。有趣的是,在控制台中一切都很好。我得到一个月,然后是所有交易,然后是一个月,依此类推。所以我在这里做错了什么,我知道它有点复杂,但请耐心等待。谢谢,如果您需要进一步的清晰度或代码,我可以回答任何问题。
解决方案
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>
);
});
}
替换forEach
为map
并查看魔术。
推荐阅读
- c++ - 如何使用c ++将sqlite数据库中的所有表从一个数据库复制到另一个数据库
- sql - Postgresql 根据另一列选择并显示一列
- python - 在 Pandas 中选择特定日期并计算值的 pct_change
- excel - 发现多次出现的 SUM INDEX MATCH
- python - 如何在 django 中添加 css、js、图像?
- xaml - Xamarin - 带有构造函数的 ViewModel,其参数作为 Xaml 中的绑定上下文
- php - 如何替换所有匹配的 $character
- c# - 一些字符替换为问号符号
- flutter - 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“*** -[NSURL initFileURLWithPath:]: nil string parameter”-_-
- java - Spring web应用+hibernate问题:通过字段表达的不满足依赖