You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何删除添加的区块?指定区块删除功能异常

React区块删除功能异常问题修复

问题根源

你遇到的删除异常问题,核心原因是使用数组index作为React元素的key。当删除中间区块后,数组的index会重新排序,React会基于key复用现有组件,导致点击删除按钮时传递的index和实际目标区块不匹配。

比如添加3个区块后,index为0、1、2;删除index=1的区块后,原index=2的区块会变成新的index=1。此时点击原第三个区块的删除按钮,实际传递的是新的index=1,会误删当前第二个区块。

修复方案

给每个区块分配唯一标识(而非依赖index),通过唯一标识来定位并删除目标区块,同时用这个唯一标识作为React元素的key:

修改后的完整代码

import { useState } from "react";
import styled from "styled-components";

const AddSection = styled.div`
  padding: 1rem;
  border: 1px solid blue;
  margin: 1rem 0;
  position: relative;
`;

const CloseBtn = styled.div`
  position: absolute;
  right: -0.5rem;
  top: -0.5rem;
  background-color: orange;
  font-size: 1rem;
  padding: 0.1rem 0.7rem;
  border-radius: 0.5rem;
  cursor: pointer;
`;

export default function App() {
  // 每个区块存储唯一id,而非空数组
  const [sections, setSections] = useState([]);
  
  const handleAdd = () => {
    // 生成唯一标识,这里用时间戳简单实现,也可以用uuid库
    const newSection = { id: Date.now() };
    setSections([...sections, newSection]);
  };
  
  const handleDelete = (targetId) => {
    // 通过id过滤数组,删除目标区块
    const updatedSections = sections.filter(section => section.id !== targetId);
    setSections(updatedSections);
  };
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div className="m-container">
        {sections.map((section, index) => {
          return (
            // 用区块的唯一id作为key
            <AddSection key={section.id} draggable="true">
              <div>Section Content {index + 1}</div>
              // 传递区块的id给删除函数
              <CloseBtn onClick={() => handleDelete(section.id)}>x</CloseBtn>
            </AddSection>
          );
        })}
        <button onClick={handleAdd}>Add Section</button>
      </div>
    </div>
  );
}

关键修改点

  • 存储结构调整:sections数组存储包含唯一id的对象,而非空数组,确保每个区块有独立标识。
  • 添加逻辑优化:新增区块时生成唯一id(Date.now()保证简单唯一性,生产环境可使用uuid库生成更可靠的唯一值)。
  • 删除逻辑重构:通过filter方法根据id过滤数组,精准删除目标区块,避免index依赖问题。
  • key值修正:使用区块的唯一id作为React元素的key,确保React能正确识别每个组件,避免复用错误。

内容的提问来源于stack exchange,提问作者clarkf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:52:48