首页 > 解决方案 > 如何将对象键设置为常量变量?

问题描述

参考下面的代码:

const item = Object.keys(data).map((key) => {
    console.log(data[key].item);
});
console.log("item -----> ", item)

const detail = () => {
    switch(item) {

      case "1":   return <CardDetailA />;
      case "2":   return <CardDetailB />;

      default:      return <CardDetailA />
    }
  }

我的数据文件

export default [
  
  {
    item: 1,
    pics: [
      './CardImg/img1.jpg',
    ],
    name: "Abby",
    age: 23,
     distance: "2 miles away",
    text:
       "On the first date I will carve our initials in a tree. It's the most romantic way to let you know I have a knife."
},

  {
    item: 2,
    pics: [
      './CardImg/img2.jpg',
    ],
    name: "Jane",
    age: 22,
    distance: "2 miles away",
    text:
      "On the first date I will carve our initials in a tree. It's the most romantic way to let you know I have a knife."
  },
];

我得到了这样的回应

在此处输入图像描述

我需要制作一个开关盒以根据项目编号返回不同的值。有什么解决方案可以让它工作吗?

标签: reactjsobject

解决方案


  • 使用时Array.map,需要在回调时返回值。在你的代码上
const item = Object.keys(data).map((key) => {
    console.log(data[key].item);
});

您只在控制台上打印了项目值并且没有返回任何内容,因此项目具有undefined值。

  • 而且dataarray,不是反对key:value,所以不需要使用Object.keys. 仅使用就足够了Array.map

const data = [
  {
    item: 1,
    pics: [
      './CardImg/img1.jpg',
    ],
    name: "Abby",
    age: 23,
    distance: "2 miles away",
    text: "On the first date I will carve our initials in a tree. It's the most romantic way to let you know I have a knife."
  },
  {
    item: 2,
    pics: [
      './CardImg/img2.jpg',
    ],
    name: "Jane",
    age: 22,
    distance: "2 miles away",
    text: "On the first date I will carve our initials in a tree. It's the most romantic way to let you know I have a knife."
  },
];

const item = data.map(({ item }) => item);
console.log("item -----> ", item)

const detail = () => {
  switch(item) {
    case "1":   return '<CardDetailA />';
    case "2":   return '<CardDetailB />';
    default:      return '<CardDetailA />';
  }
}


推荐阅读