保存到钩子数组时出错:对象不可迭代
2022-06-09
674
大家好。 我试图在用户单击产品按钮后将对象存储到钩子数组中。 但是,我一直收到:对象不可迭代错误。
主要部分:
let shoppingArray = [];
const shopping = (item) => {
shoppingArray.push(item);
console.log(shoppingArray);
setShoppingBag(...shoppingBag, shoppingArray);
};
...
<ShoppingCartOutlinedIcon className="icons" onClick={() => shopping(item)}></ShoppingCartOutlinedIcon>
错误代码:
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
更新
为什么这里不起作用?
const [shoppingBag, setShoppingBag] = React.useState([]);
const shopping = (item) => {
setShoppingBag(...shoppingBag, item);
};
2个回答
setShoppingBag([...shoppingBag, ...shoppingArray]);
Tung Nguyen
2022-06-09
函数调用中缺少数组 []。
setShoppingBag(...shoppingBag, shoppingArray);
应为
setShoppingBag([...shoppingBag, shoppingArray]);
Tea_Lover_418
2022-06-09