react hooks实现列表
使用 React Hooks 实现列表
React Hooks 提供了一种简洁的方式来管理状态和副作用,非常适合实现动态列表功能。以下是几种常见的实现方法:
基础列表实现
通过 useState 管理列表数据,结合 map 方法渲染列表项:
import React, { useState } from 'react';
function TodoList() {
const [items, setItems] = useState(['Item 1', 'Item 2']);
const [inputValue, setInputValue] = useState('');
const addItem = () => {
setItems([...items, inputValue]);
setInputValue('');
};
return (
<div>
<input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button onClick={addItem}>Add</button>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
带删除功能的列表
扩展基础列表,添加删除功能:
const removeItem = (indexToRemove) => {
setItems(items.filter((_, index) => index !== indexToRemove));
};
// 在渲染部分添加删除按钮
{items.map((item, index) => (
<li key={index}>
{item}
<button onClick={() => removeItem(index)}>Delete</button>
</li>
))}
性能优化列表
对于大型列表,使用 React.memo 和 useCallback 优化性能:
const MemoizedItem = React.memo(function Item({ item, onDelete }) {
return (
<li>
{item}
<button onClick={onDelete}>Delete</button>
</li>
);
});
function OptimizedList() {
const [items, setItems] = useState(/*...*/);
const handleDelete = useCallback((index) => {
setItems(prev => prev.filter((_, i) => i !== index));
}, []);
return (
<ul>
{items.map((item, index) => (
<MemoizedItem
key={index}
item={item}
onDelete={() => handleDelete(index)}
/>
))}
</ul>
);
}
异步数据列表
使用 useEffect 和 useState 处理异步数据加载:
function AsyncList() {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/items')
.then(res => res.json())
.then(data => {
setItems(data);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
可排序列表
实现拖拽排序功能需要结合第三方库如 react-beautiful-dnd:
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
function SortableList() {
const [items, setItems] = useState(/*...*/);
const onDragEnd = (result) => {
if (!result.destination) return;
const newItems = Array.from(items);
const [removed] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, removed);
setItems(newItems);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="list">
{(provided) => (
<ul ref={provided.innerRef} {...provided.droppableProps}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<li
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
);
}
关键注意事项
- 始终为列表项提供稳定的
key属性(避免使用索引作为 key 当列表会变化时) - 复杂状态更新使用函数式更新确保准确性:
setItems(prev => [...prev, newItem]) - 大型列表考虑虚拟滚动技术(如
react-window库) - 表单输入需要受控组件管理(如示例中的
inputValue状态)







