reactjs - 如何将对象键设置为常量变量?
问题描述
参考下面的代码:
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."
},
];
我得到了这样的回应
我需要制作一个开关盒以根据项目编号返回不同的值。有什么解决方案可以让它工作吗?
解决方案
- 使用时
Array.map
,需要在回调时返回值。在你的代码上
const item = Object.keys(data).map((key) => {
console.log(data[key].item);
});
您只在控制台上打印了项目值并且没有返回任何内容,因此项目具有undefined
值。
- 而且
data
是array
,不是反对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 />';
}
}
推荐阅读
- android - AudioPlaybackCapture API 用于通话录音
- c# - 用 4 个算术运算符计算一个简单的语句不起作用
- javascript - Node.js 服务器未发送响应,或客户端未接收
- deep-learning - 回归器的初始化是什么?
- vb.net - 有没有一种方法可以使用 WebRequest 类在 80 以外的另一个端口上查询服务器?
- jquery - 如何让用户从下拉菜单中只选择一个选项?
- python - 将程序添加到 PATH 有什么意义?
- php - centOS 7上缺少Nginx default.conf
- javascript - 从 p:selectedCheckbox javascript 获取值复选框
- python - 计算字符串在特定列中出现的次数