【发布时间】:2021-02-07 02:23:32
【问题描述】:
我正在从skidList 数组创建列表,并处理每个skid 上的复制和删除操作以及单击删除按钮我正在调用deleteSkid 方法,该方法删除该索引处的skid 并更新列表。
但是,它不会删除特定索引处的skid,而是删除数组列表中的最后一个skid。
const CreateNewTab = () => {
const [skidList, setSkidList] = useState([]);
const [productNameMap, setproductNameMap] = useState({});
useEffect(() => {
let skidList = [];
let newSkid = {};
newSkid["2"] = "0";
newSkid["3"] = "0";
newSkid["4"] = "0";
skidList.push(newSkid);
setSkidList([...skidList]);
let productNameMap = {};
productNameMap["2"] = "PEN";
productNameMap["3"] = "PENCIL";
productNameMap["4"] = "ERASER";
setproductNameMap({ ...productNameMap });
}, []);
const updateProductQuantity = (skid, key, newQuantity, index) => {
console.log("Inside update Skid Quantity Index= " + index);
skid[key] = newQuantity;
let newSkidList = skidList;
newSkidList.splice(index, 1, skid);
console.log(newSkidList);
setSkidList([...newSkidList]);
};
const deleteSkid = (index) => {
console.log(index);
let newSkidList = skidList;
newSkidList.splice(index, 1);
console.log("Skid deleted from: " + newSkidList);
setSkidList([...newSkidList]);
};
const insertSkid = (skid) => {
setSkidList(skidList.concat([{ ...skid }]));
};
return (
<div>
{skidList.flatMap((skid, index) => (
<div style={{ marginRight: "0", paddingRight: "0" }}>
<Row style={{ margin: "0", padding: "0" }}>
<Col span={19}>
{Object.keys(skid).map((key) => (
<Row>
<Col span={16}>
<h6>{productNameMap[key.toString()]}</h6>
</Col>
<Col span={8}>
<InputNumber
min={0}
defaultValue={skid[key]}
rules={[
{
required: true,
message: "Please input quantity!",
},
]}
onChange={(newQuantity) => {
updateProductQuantity(skid, key, newQuantity, index);
}}
/>
</Col>
</Row>
))}
</Col>
<Col span={5}>
<Row>
<Col span={12}>
<Button
type="primary"
icon={<CopyOutlined />}
size="large"
shape="circle"
onClick={() => insertSkid(skid)}
/>
</Col>
<Col spna={12}>
<Button
type="primary"
size="large"
shape="circle"
danger
icon={<DeleteOutlined />}
onClick={() => deleteSkid(index)}
/>
</Col>
</Row>
}
</Col>
</Row>
<Divider />
</div>
))}
</div>
);
};
【问题讨论】:
-
你为什么使用
.flatMap? -
我尝试使用 .map 并遇到同样的问题。
-
您是否尝试过在
flatMap内的父元素上使用key属性,就像这样<div key={index} style={{ marginRight: "0", paddingRight: "0" }}>? -
是的,我尝试按照您的建议使用 key prop。它不能解决问题。
标签: javascript reactjs ecmascript-6 antd