javascript - React - 更新状态数组时对象中的唯一键被覆盖
问题描述
我有一个将商品添加到购物车的功能。单击按钮时,我正在尝试为新对象项生成唯一键。我是new Date().getTime()
根据点击频率来做的。我在函数内部测试了 console.log,它unique_id
为每个新对象生成不同的数字。当我尝试将现有的对象状态数组与新item
对象组合时,问题就开始了。所有现有unique_id
的 s 都会被覆盖到最新的unique_id
. 我还在为状态数组使用 React useState 钩子。React 有点相关,因为状态数组不应该直接编辑,而是通过 setter 方法。
我尝试了.push
, .concat
, Array.from
, 扩展运算符的组合,在函数内部和外部循环和分配变量。我知道这是一种pass-by-reference
vspass-by-value
情况,因为这些数组方法只是浅拷贝。
const [cart, setCart] = useState([])
const addItem = (item) => {
let cartArr = cart
item['unique_id'] = new Date().getTime()
setCart([...cartArr, item])
}
预期的:
[
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696123},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696256},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377}
]
但得到:
[
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377},
{id: 1, price: 10.11, title: "The Art Of War", unique_id: 1565675696377}
]
解决方案
而不是推送数组中的值,您可以连接数组和对象,请参阅下面的代码供您参考
const [cart, setCart] = useState([]);
const addItem = item => {
item["unique_id"] = new Date().getTime();
setCart([...cart, item]);
};
推荐阅读
- java - 如何将 Spring Boot 非 Web 应用程序部署到 Weblogic Server
- r - 将绘图标题添加到仪表图并调整输出
- javascript - 在 HTML 表单不工作的情况下使用 on.("submit")
- random - Hive:从分组中随机选择不同大小的样本
- python - QStateMachine 过程转换(即信号)
- ms-access - 如何连接组合框中的值和访问中的数字字段
- javascript - 我想通过 google map api 检测用户位置
- java - Android Studio - 如何调用引用可绘制对象的方法?
- python - 如何检测龟蟒中两个物体之间的碰撞?
- html - 使用 css 样式输入单选