react 如何遍历
遍历数组
在React中遍历数组通常使用map方法,它会返回一个新的数组。map是处理数组并渲染列表元素的首选方法。
const items = ['Apple', 'Banana', 'Cherry'];
function ItemList() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
遍历对象
对于对象,可以使用Object.keys()、Object.values()或Object.entries()方法将其转换为数组后再遍历。

const person = { name: 'John', age: 30, occupation: 'Developer' };
function PersonDetails() {
return (
<ul>
{Object.entries(person).map(([key, value]) => (
<li key={key}>
{key}: {value}
</li>
))}
</ul>
);
}
条件渲染
在遍历时可能需要结合条件判断,可以使用三元运算符或逻辑与运算符。
const numbers = [1, 2, 3, 4, 5];
function NumberList() {
return (
<ul>
{numbers.map((number) =>
number % 2 === 0 ? <li key={number}>{number} is even</li> : null
)}
</ul>
);
}
使用Fragment
当需要返回多个元素而不想添加额外DOM节点时,可以使用React.Fragment。

const tags = ['React', 'JavaScript', 'HTML'];
function TagList() {
return (
<>
{tags.map((tag) => (
<React.Fragment key={tag}>
<span>{tag}</span>
<br />
</React.Fragment>
))}
</>
);
}
性能优化
对于大型列表,建议使用key属性来提高性能,避免使用索引作为key,应使用唯一标识符。
const todos = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a project' },
];
function TodoList() {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
自定义渲染函数
可以将遍历逻辑抽象为独立的渲染函数,提高代码可读性。
const products = [
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Phone', price: 699 },
];
function renderProduct(product) {
return (
<div key={product.id}>
<h3>{product.name}</h3>
<p>${product.price}</p>
</div>
);
}
function ProductList() {
return <div>{products.map(renderProduct)}</div>;
}






