当前位置:首页 > React

react hooks实现列表

2026-01-27 05:39:50React

使用 React Hooks 实现列表

React Hooks 提供了一种简洁的方式来管理状态和副作用,非常适合实现动态列表功能。以下是几种常见的实现方法:

基础列表实现

通过 useState 管理列表数据,结合 map 方法渲染列表项:

react hooks实现列表

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.memouseCallback 优化性能:

react hooks实现列表

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>
  );
}

异步数据列表

使用 useEffectuseState 处理异步数据加载:

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 状态)

标签: 列表react
分享给朋友:

相关文章

vue实现列表水印

vue实现列表水印

实现列表水印的方法 在Vue中为列表添加水印可以通过多种方式实现,以下是几种常见的方法: 使用CSS背景图 通过CSS的background-image属性为列表元素添加水印背景。水印可以是文字或图…

h5实现展开列表

h5实现展开列表

使用HTML5和CSS实现展开列表 在HTML5中,可以通过结合CSS和JavaScript实现展开列表效果。以下是几种常见的方法: 方法1:使用details和summary标签 HTML5提供…

react 如何分页

react 如何分页

分页实现方法 在React中实现分页功能可以通过多种方式完成,具体取决于数据来源(如API或本地数据)和UI库的选择。以下是常见的实现方法: 使用本地数据分页 对于存储在组件状态或Context中…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何验证

react如何验证

表单验证方法 在React中验证表单数据通常使用以下几种方式: 内置HTML5验证 利用HTML5原生表单验证属性如required、pattern等,结合form.noValidate属性禁用浏览…

理解如何react

理解如何react

理解React的核心概念 React是一个用于构建用户界面的JavaScript库,专注于通过组件化开发提高代码的可维护性和复用性。其核心思想包括虚拟DOM(Virtual DOM)和单向数据流,能够…