ES6 - 解构和 For of Loop only returns first object
ES6 - Destructuring and For of Loop only returns first object
我有一个循环遍历以下对象的 React 应用程序:
const topics = [
{name: 'Mon', color: 'blue', id: 1},
{name: 'Tue', color: 'red', id: 2},
{name: 'Wed', color: 'pink', id: 3},
]
我正在尝试通过 for of loop
在我的功能组件
中解构和循环对象
export const Data = () => {
for (let {name, color, id} of topics) {
console.log(name, color, id) //Only first iteration is outputted
return (
<div key={id}>
<div>{name}</div>
<div>{color}</div>
</div>
)
}
}
我只得到 1, Mon, blue
我错过了什么?这与 return
或 render
相关吗?
For of Loop only returns first object, Why?
因为您在 for...of 正文中使用了 return 语句,这打破了循环并 returning 结果。删除 return 并检查它是否会打印所有值。
检查这个片段:
const topics = [
{name: 'Mon', color: 'blue', id: 1},
{name: 'Tue', color: 'red', id: 2},
{name: 'Wed', color: 'pink', id: 3},
]
for (let {name, color, id} of topics) {
console.log(name, color, id);
}
要渲染所有数据使用#array.map而不是for...of循环,这样写:
export const Data = () => (
<div>
{
topics.map( ({ name, color, id }) => {
return (
<div key={id}>
<div>{name}</div>
<div>{color}</div>
</div>
)
})
}
</div>
)
在您提出的评论中:
How could I loop and still return/render the all the data as JSX?
您 return 一个包含元素的数组,通常使用 Array#map
:
export const Data = () => {
return topics.map(({name, color, id}) => (
<div key={id}>
<div>{name}</div>
<div>{color}</div>
</div>
));
};
旁注:虽然您可以在自己的代码中做任何您想做的事情,但 JavaScript 中的 压倒性的 约定是只有构造函数以大写字母开头。所有其他函数均以小写字母开头。
我有一个循环遍历以下对象的 React 应用程序:
const topics = [
{name: 'Mon', color: 'blue', id: 1},
{name: 'Tue', color: 'red', id: 2},
{name: 'Wed', color: 'pink', id: 3},
]
我正在尝试通过 for of loop
在我的功能组件
export const Data = () => {
for (let {name, color, id} of topics) {
console.log(name, color, id) //Only first iteration is outputted
return (
<div key={id}>
<div>{name}</div>
<div>{color}</div>
</div>
)
}
}
我只得到 1, Mon, blue
我错过了什么?这与 return
或 render
相关吗?
For of Loop only returns first object, Why?
因为您在 for...of 正文中使用了 return 语句,这打破了循环并 returning 结果。删除 return 并检查它是否会打印所有值。
检查这个片段:
const topics = [
{name: 'Mon', color: 'blue', id: 1},
{name: 'Tue', color: 'red', id: 2},
{name: 'Wed', color: 'pink', id: 3},
]
for (let {name, color, id} of topics) {
console.log(name, color, id);
}
要渲染所有数据使用#array.map而不是for...of循环,这样写:
export const Data = () => (
<div>
{
topics.map( ({ name, color, id }) => {
return (
<div key={id}>
<div>{name}</div>
<div>{color}</div>
</div>
)
})
}
</div>
)
在您提出的评论中:
How could I loop and still return/render the all the data as JSX?
您 return 一个包含元素的数组,通常使用 Array#map
:
export const Data = () => {
return topics.map(({name, color, id}) => (
<div key={id}>
<div>{name}</div>
<div>{color}</div>
</div>
));
};
旁注:虽然您可以在自己的代码中做任何您想做的事情,但 JavaScript 中的 压倒性的 约定是只有构造函数以大写字母开头。所有其他函数均以小写字母开头。