React中数组最后一项复制功能异常问题求助
问题分析与修复
你的代码存在三个关键问题,导致最后一项复制功能失效,同时还隐藏着删除功能的潜在问题:
1. 复制功能的索引传递错误
在Type1组件的copyHandler中,你调用copyItems时传入了index + 1,但copyItems函数的设计是接收目标元素的原始索引,而非索引+1。当操作最后一项时(比如数组长度为2,最后一项索引是1),传入index + 1 = 2,此时list[2]会是undefined,导致复制出无效的空对象,同时插入位置也会出错。
修复:直接传递index给copyItems:
const copyHandler = () => setType1Options(copyItems(type1Options, index));
2. 删除功能的参数与索引错误
Type1组件的deleteHandler定义了参数index,但点击按钮时没有传递任何参数,此时函数内的index实际是点击事件对象,而非组件的props.index。同时你错误地使用index + 1调用deleteItems,会导致删除错误的元素。
修复:移除函数参数,直接使用props.index,且不需要+1:
const deleteHandler = () => setType1Options(deleteItems(type1Options, index));
3. List组件中Type2的props传递错误
在List组件渲染Type2时,你错误地将setType2Options传给了setType1Options属性,这会导致Type2的操作错误地修改Type1的状态。
修复:将属性名改为setType2Options:
<Type2 index={index} obj={obj} type2Options={type2Options} setType2Options={setType2Options} />
修复后的关键代码片段
Type1组件
import "./styling.css"; import { deleteItems, copyItems } from "./utils"; export default function Type1(props) { const { index, obj, type1Options, setType1Options } = props; const copyHandler = () => setType1Options(copyItems(type1Options, index)); const deleteHandler = () => setType1Options(deleteItems(type1Options, index)); return ( <div className="box-container"> <div className="box-header"> <h3>Index {index + 1}</h3> <div className="box-buttons"> <button onClick={copyHandler}>Copy</button> <button onClick={deleteHandler}>Delete</button> </div> </div> <div className="box-content"> {obj.name}: {obj.value} </div> </div> ); }
List组件(Type2渲染部分)
<div> Category 2 {type2Options.map((obj, index) => ( <Type2 index={index} obj={obj} type2Options={type2Options} setType2Options={setType2Options} /> ))} </div>
最后需要确保Type2组件的逻辑和Type1保持一致(修正复制、删除函数的索引传递),这样两个类别的功能都能正常运行。
内容的提问来源于stack exchange,提问作者lrr59
相关产品推荐
相关产品推荐

