You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将const itemsProject数组改写为返回相同内容的ItemsProject函数

实现方案

你可以直接将常量数组声明替换为函数声明,在函数内部返回与原数组内容完全一致的结构即可。另外注意你提供的原始代码存在语法问题:两个数组元素对象之间缺少逗号,已在下方代码中修正:

function onClick(e, item) {}

function ItemsProject() {
  return [
    {
      name: 'companies',
      label: translate('sidebarProjectCompanies'),
      Icon: CompanyIcon,
      path: '/project/:id/companies',
      onClick,
    },
    {
      name: 'currencies',
      label: translate('sidebarProjectCurrencies'),
      Icon: CurrencyIcon,
      path: '/project/:id/currencies',
      onClick,
    }
  ];
}

export default ItemsProject;

注意事项

  • 后续需要使用数组内容时,调用ItemsProject()即可得到和原itemsProject常量完全一致的返回值
  • 该写法每次调用都会生成新的数组实例,可避免引用类型的全局污染问题,如果需要复用同一个实例,可以将数组提取到函数外部缓存:
function onClick(e, item) {}

const innerItems = [
  {
    name: 'companies',
    label: translate('sidebarProjectCompanies'),
    Icon: CompanyIcon,
    path: '/project/:id/companies',
    onClick,
  },
  {
    name: 'currencies',
    label: translate('sidebarProjectCurrencies'),
    Icon: CurrencyIcon,
    path: '/project/:id/currencies',
    onClick,
  }
]
function ItemsProject() {
  return innerItems
}

export default ItemsProject;

内容的提问来源于stack exchange,提问作者Cleiton Freitas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:54:02