javascript - 如何使用 onChange 方法更新数组中的对象
问题描述
我正在从 skidList 数组创建列表,并处理每个撬块上的复制和删除操作以及InputNumber
(数量)的更改,我正在调用updateProductQuantity
更新该撬块中产品数量的方法。
但是,它不会更新特定撬块的产品数量,而是更新阵列列表中所有撬块的数量。
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) => {
let newSkidList = skidList;
newSkidList.push(skid);
console.log("New Skid Inserted: "+newSkidList);
setSkidList([...newSkidList]);
};
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>
)}
解决方案
您的insertSkid
函数似乎正在向skid
列表中添加对已存在对象的另一个引用。由于您的列表包含对同一对象的多个引用,因此修改一个索引将影响所有索引,因为它们都指向同一对象。
如果您的意图insertSkid
是插入现有滑动对象的克隆,您将需要使用对象扩展之类的东西:
const insertSkid = skidToClone => {
setSkidList(skidList.concat([{ ...skidToClone }]));
};
推荐阅读
- javascript - 如何获得位于两侧的字符/单词,我们选择的字符落在它们之间?
- c++ - 重构使用动态转换的 std::set 的比较运算符
- ios - 如何从 iOS 模拟器将日志输出到终端?
- c++ - 将 C++ 方法作为函数指针传递
- language-agnostic - 源自有向循环图中每个节点的每个子图的大小
- udp - gstreamer 的 udpsink 在发送约 1000 个数据包后停止流式传输
- list - 在颤动的列表视图中搜索
- javascript - 未捕获的语法错误:无法在模块外部使用导入语句 - Javascript
- python - 为什么我在 Django 中重新加载页面时图片会消失?
- c# - 将日期时间转换为另一种格式