首页 > 解决方案 > 如何在 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>
)

标签: javascriptreactjs

解决方案


根据数组的长度测试索引。

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});


推荐阅读