在javascript(客户端ReactJS)中克隆对象数组的索引,并使用map方法返回基于新数组的视图



我有一个ReactJS应用程序,在一个组件中,我有一张表,我在组件视图(JSX(中使用map((方法创建每一行表,其中每一行都有一个重复按钮,这样用户就可以复制一行,并在单击的项目下看到它。例如:如果用户单击第二行重复按钮,我想克隆页面数据数组的索引1,并基于新数组更新组件视图。

这是简化的代码:

import React, {useState} from 'react';
const MyComponent = () => {
const [PageData, setPageData] = useState([
{name: "item1", id: "1"},
{name: "item2", id: "2"},
{name: "item3", id: "3"}
])
const duplicateItem = (RowItem, i) => {
let RowsData = [...PageData];
let Index = parseInt(i + 1);
RowsData.splice(Index, 0, Duplicate);
setPageData(RowsData);
}
return (
<div>
{PageData.map((Item, i) =>(
<div className="form-row" key={i}>
<p>{Item.name}</p>
<button
onClick={() => duplicateItem(Item, i)}
className="duplicate"
>
</button>
</div>
))}
</div>
)
}
export default MyComponent;

我们预计会发生的情况是,当用户单击复制按钮时,在用户单击的项目下会添加一行(如果他们复制第二个项目,它的副本将出现在第二个项下(,我不知道为什么这个代码不起作用,今天是我的截止日期,所以我需要帮助。

您可以按照如下所示进行操作。

为了简单起见,我使用了数组长度来更新新添加的重复项的id。此外,在duplicateItem中,您已经收到要复制的项目,因此我们可以使用相同的方法添加到所选项目下面。

const {useState} = React;
const MyComponent = () => {
const [PageData, setPageData] = useState([
{name: "item1", id: "1"},
{name: "item2", id: "2"},
{name: "item3", id: "3"}
])
const duplicateItem = (RowItem, i) => {
setPageData(data => {
let RowsData = [...data];
//Create a new ID, for simplicity I'm just using the length of the array
const id = `${RowsData.length + 1}`;
//Add the same item with new id below the selected item
const Index = parseInt(i + 1);
RowsData.splice(Index, 0, {...RowItem, id});
return RowsData;
});
}
return (
<div>
{PageData.map((Item, i) =>(
<div className="form-row" key={i}>
<p>{Item.name}_{Item.id}</p>
<button
onClick={() => duplicateItem(Item, i)}
className="duplicate"
>
</button>
</div>
))}
</div>
)
}
ReactDOM.render(<MyComponent />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>

最新更新