react实现列表
使用 React 实现列表
React 中实现列表通常使用 map 方法遍历数组并渲染每个元素。以下是几种常见的实现方式:
基础列表渲染
const items = ['Apple', 'Banana', 'Orange'];
function List() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
使用对象数组
当列表项包含更多属性时,可以使用对象数组:
const products = [
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Phone', price: 699 },
{ id: 3, name: 'Tablet', price: 499 }
];
function ProductList() {
return (
<div>
{products.map(product => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>${product.price}</p>
</div>
))}
</div>
);
}
带状态的可变列表
对于需要动态添加/删除的列表,可以使用 useState:
import { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a project' }
]);
const [input, setInput] = useState('');
const addTodo = () => {
if (input.trim()) {
setTodos([...todos, { id: Date.now(), text: input }]);
setInput('');
}
};
return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</div>
);
}
性能优化
对于大型列表,使用 React.memo 和 虚拟滚动:
const MemoizedItem = React.memo(function Item({ item }) {
return <li>{item.text}</li>;
});
function BigList({ items }) {
return (
<ul>
{items.map(item => (
<MemoizedItem key={item.id} item={item} />
))}
</ul>
);
}
关键注意事项
- 每个列表项必须有唯一的
key属性 key应该来自数据中的唯一标识,而不是数组索引- 避免在渲染时修改原始数组
- 复杂列表考虑使用虚拟滚动库如
react-window







