当前位置:首页 > React

react实现增删改

2026-01-26 19:31:14React

React 实现增删改功能

在 React 中实现增删改(CRUD)功能是常见的需求,通常通过状态管理和事件处理来完成。以下是具体实现方法:

状态初始化

使用 useState 初始化数据状态和管理表单输入:

react实现增删改

const [items, setItems] = useState([
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' }
]);
const [inputValue, setInputValue] = useState('');
const [editingId, setEditingId] = useState(null);

添加功能

通过表单提交事件将新项添加到状态数组:

const handleAdd = (e) => {
  e.preventDefault();
  if (!inputValue.trim()) return;

  const newItem = {
    id: Date.now(),
    name: inputValue
  };

  setItems([...items, newItem]);
  setInputValue('');
};

删除功能

通过过滤数组实现删除指定项:

react实现增删改

const handleDelete = (id) => {
  setItems(items.filter(item => item.id !== id));
};

更新功能

分两步实现:先设置编辑状态,再提交更新:

const handleEdit = (item) => {
  setEditingId(item.id);
  setInputValue(item.name);
};

const handleUpdate = (e) => {
  e.preventDefault();

  setItems(items.map(item => 
    item.id === editingId 
      ? { ...item, name: inputValue } 
      : item
  ));

  setEditingId(null);
  setInputValue('');
};

完整组件示例

function CrudExample() {
  const [items, setItems] = useState([
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' }
  ]);
  const [inputValue, setInputValue] = useState('');
  const [editingId, setEditingId] = useState(null);

  const handleAdd = (e) => {
    e.preventDefault();
    if (!inputValue.trim()) return;

    const newItem = {
      id: Date.now(),
      name: inputValue
    };

    setItems([...items, newItem]);
    setInputValue('');
  };

  const handleDelete = (id) => {
    setItems(items.filter(item => item.id !== id));
  };

  const handleEdit = (item) => {
    setEditingId(item.id);
    setInputValue(item.name);
  };

  const handleUpdate = (e) => {
    e.preventDefault();

    setItems(items.map(item => 
      item.id === editingId 
        ? { ...item, name: inputValue } 
        : item
    ));

    setEditingId(null);
    setInputValue('');
  };

  return (
    <div>
      <form onSubmit={editingId ? handleUpdate : handleAdd}>
        <input
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">
          {editingId ? 'Update' : 'Add'}
        </button>
      </form>

      <ul>
        {items.map(item => (
          <li key={item.id}>
            {item.name}
            <button onClick={() => handleEdit(item)}>Edit</button>
            <button onClick={() => handleDelete(item.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

使用 useReducer 管理复杂状态

对于更复杂的状态逻辑,可以使用 useReducer

const initialState = {
  items: [],
  inputValue: '',
  editingId: null
};

function reducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM':
      return {
        ...state,
        items: [...state.items, action.payload],
        inputValue: ''
      };
    case 'DELETE_ITEM':
      return {
        ...state,
        items: state.items.filter(item => item.id !== action.payload)
      };
    // 其他 case...
    default:
      return state;
  }
}

// 在组件中使用
const [state, dispatch] = useReducer(reducer, initialState);

注意事项

  • 确保为列表项设置唯一的 key 属性
  • 复杂的表单验证建议使用 Formik 等库
  • 对于大型应用,考虑使用 Context API 或状态管理库(如 Redux)
  • 与后端交互时,注意异步操作的处理(如 axios 请求)

标签: react
分享给朋友:

相关文章

react如何使用

react如何使用

React 的基本使用 React 是一个用于构建用户界面的 JavaScript 库,以下是一些核心概念和使用方法。 安装 React 通过 create-react-app 快速搭建 React…

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: node…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

理解如何react

理解如何react

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

如何启动react

如何启动react

安装Node.js 确保系统已安装Node.js(建议使用LTS版本),可通过官网下载并安装。安装完成后,在终端运行以下命令验证版本: node -v npm -v 创建React项目 使用官方工具…