我有一个具有以下格式的对象数组
const [type1Options, setType1Options] = useState([
{
name: "Name1",
value: "Value1",
},
{
name: "Name2",
value: "Value2",
},
]);
const [type2Options, setType2Options] = useState([
{
name: "Name1",
value: "Value1",
},
{
name: "Name2",
value: "Value2",
},
]);
我正在按每个条目的复制和删除按钮按类别渲染这些对象。删除将从数组中删除条目,复制会将单击的项目内容复制到新条目中,并放置在单击的条目的正下方。删除工作正常,但复制最后一个条目无法按预期工作。有人可以帮忙吗?
沙箱:https://codesandbox.io/p/sandbox/i18-demo-7594gf?file=%2Fsrc%2FApp.js%3A5%2C2-24%2C6
用于复制和删除功能的实用程序
export const deleteItems = (list, idx) => {
const temp = [...list];
temp.splice(idx, 1);
return temp;
};
export const copyItems = (list, idx) => {
const newItem = { ...list[idx] };
const newItems = [...list.slice(0, idx + 1), newItem, ...list.slice(idx + 1)];
return newItems;
};
import { useState } from "react";
import List from "./List";
export default function App() {
const [type1Options, setType1Options] = useState([
{
name: "Name1",
value: "Value1",
},
{
name: "Name2",
value: "Value2",
},
]);
const [type2Options, setType2Options] = useState([
{
name: "Name1",
value: "Value1",
},
{
name: "Name2",
value: "Value2",
},
]);
return (
<div>
<List
type1Options={type1Options}
type2Options={type2Options}
setType1Options={setType1Options}
setType2Options={setType2Options}
/>
</div>
);
}
import Type1 from "./Type1";
import Type2 from "./Type2";
export default function List(props) {
const { type1Options, type2Options, setType1Options, setType2Options } =
props;
return (
<>
<div>
Category 1
{type1Options.map((obj, index) => (
<Type1
index={index}
obj={obj}
type1Options={type1Options}
setType1Options={setType1Options}
/>
))}
</div>
<br />
<div>
Category 2
{type2Options.map((obj, index) => (
<Type2
index={index}
obj={obj}
type2Options={type2Options}
setType1Options={setType2Options}
/>
))}
</div>
</>
);
}
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 + 1));
const deleteHandler = (index) =>
setType1Options(deleteItems(type1Options, index + 1));
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>
);
}