如何在 React 中循环对象
在 React 中循环一个对象:
- 使用
Object.keys()
方法获取对象键的数组。 - 使用
map()
方法遍历键数组。
export default function App() {
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
return (
<div>
{/* ?️ iterate object KEYS */}
{Object.keys(employee).map((key, index) => {
return (
<div key={index}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
<br />
<br />
<br />
{/* ?️ iterate object VALUES */}
{Object.values(employee).map((value, index) => {
return (
<div key={index}>
<h2>{value}</h2>
<hr />
</div>
);
})}
</div>
);
}
我们使用 Object.keys
方法来获取对象键的数组。
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
// ?️ ['id', 'name', 'salary']
console.log(Object.keys(employee));
// ?️ [1, '火焰兔', 123]
console.log(Object.values(employee));
我们只能在数组上调用 map()
方法,因此我们需要获取对象键的数组或对象的值。
我们传递给 Array.map
方法的函数会使用数组中的每个元素和当前迭代的索引来调用。
我们在示例中使用了 key
prop
的索引,但是如果你有一个稳定的、唯一的标识符,最好使用它。
在迭代对象的键时,将对象的键用于 key prop 是安全的,因为对象中的键保证是唯一的。
export default function App() {
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
return (
<div>
{/* ?️ iterate object KEYS */}
{Object.keys(employee).map(key => {
return (
<div key={key}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
</div>
);
}
但是,如果我们正在迭代对象的值,则不能安全地使用 key 属性的值,除非我们可以确定对象中的所有值都是唯一的。
出于性能原因,React 在内部使用 key prop。 它有助于库确保仅重新渲染已更改的数组元素。
话虽如此,除非我们处理数千个数组元素,否则我们不会看到使用索引和稳定的唯一标识符之间有任何明显的区别。
在 React 中循环遍历对象的值:
- 使用
Object.values()
方法获取对象值的数组。 - 使用
map()
方法迭代值数组。
export default function App() {
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
return (
<div>
{/* ?️ iterate object VALUES */}
{Object.values(employee).map((value, index) => {
return (
<div key={index}>
<h2>{value}</h2>
<hr />
</div>
);
})}
</div>
);
}
我们使用 Object.values
方法来获取对象值的数组。
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
// ?️ [1, '火焰兔', 123]
console.log(Object.values(employee));
如果我们只想渲染对象的值,我们可以使用这种方法直接访问它们。
我们还可以使用 Object.entries
方法,该方法返回一个键值对数组的数组。
export default function App() {
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
console.log(Object.entries(employee));
return (
<div>
{Object.entries(employee).map(([key, value]) => {
return (
<div key={key}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
</div>
);
}
下面是 Object.entries()
方法的输出的样子。
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
// ?️ [
// ['id', 1],
// ['name', '火焰兔'],
// ['salary', 123],
// ]
const result = Object.entries(employee);
console.log(result);
该方法返回一个包含键值对子数组的数组。
另一种方法是使用 Array.forEach()
方法来迭代对象的键并将 JSX 元素推送到一个数组中,然后我们会渲染该数组。
export default function App() {
const employee = {
id: 1,
name: '火焰兔',
salary: 123,
};
const results = [];
Object.keys(employee).forEach(key => {
results.push(
<h2 key={key}>
{key}: {employee[key]}
</h2>,
);
});
return (
<div>
{results}
</div>
);
}
每个键都会调用 Array.forEach()
方法,但是 forEach()
方法返回 undefined,所以我们不能直接在 JSX 代码中使用它。
相反,我们将 JSX 元素推送到我们渲染的数组中。
注意
,这是一种更间接的方法,我们不会看到它在 React 应用程序中经常使用。