javascript - 如何在 React 中获取地图函数中的最后一项
问题描述
我有一组从 CMS 返回给我的数据。我映射每个项目并返回一个带有相应数据的组件。但是,我需要在方法中定位.map
函数中的最后一项,render
因为最后一项需要一些修改。
我该怎么做?
return (
<div>
{data.body.map((item, i) => {
console.log(i);
if (item.type === 'button') {
return <ButtonComponent color="ffffff" bgColor="4C319D" text={item.text} textAlign="left" id={item.id} />
}
})}
</div>
)
解决方案
根据数组的长度测试索引。
const array = ['a', 'b', 'c', 'd'];
const mapped = array.map(
(value, index, array) => {
if (array.length - 1 === index) {
console.log(`${value} is the last item in the array`);
return `-->${value.toUpperCase()}<--`;
} else {
return value.toLowerCase();
}
}
);
console.log({mapped});
推荐阅读
- angular - Angular 组件中的链接不起作用看起来无法单击
- ruby-on-rails - ActiveRecord::ConnectionAdapters::OracleEnhancedConnectionException "DESC 表名,它存在吗?" 为测试设置运行迁移时出错
- c# - 在 c# 应用程序中使用 python 的最佳实践是什么?
- python - 递归 Python 函数严重影响 Django 站点性能
- c - 如何根据条件将一个数组中的元素添加到另一个未定义大小的数组中?
- java - JSch 库 Kerberos 支持
- ios - iOS:如何在我的应用程序中更改 alertView 的每个文本、标题、按钮的每种字体?
- vb.net - 如何从 Dbnull 类型转换为 Date 类型
- angular - 如何在Angular 6中的Ngx-bootstrap模态中将组件作为模态体传递
- java - JComboBox 并不总是将值保存到 TableModel