[英]Set State in a loop React Native
我有一些对象数组形式的道具,我用它们来更新我的“项目”state。我能够遍历对象并构建包含“product_id”和“数量”的对象。 当我只是 console.log 时,我可以看到正确的数据,但是当我尝试更新 state 时,我收到错误"Too many re-renders, react limits the number of renders to prevent an infinite-loop."
const [items, setItems] = useState(
{
product_id: 93,
quantity: 2,
},
{
product_id: 22,
variation_id: 23,
quantity: 1,
},
);
const cart = props.cart;
Object.keys(cart).forEach(function (key) {
const prod = {
product_id: cart[key].id,
quantity: cart[key].quantity,
};
setItems((currentItems) => {
return {prod, ...currentItems};
});
});
编辑我的购物车道具是使用以下代码从 redux 中提取的
function mapStateToProps(state) {
return {
cart: state.cart,
};
}
export default connect(mapStateToProps)(Checkout);
问题是这个 prop 的属性不仅仅是我需要的数量和 id。
您不需要在循环中一次又一次地设置 state。 相反,只是在数组上循环,获取项目并最终设置 state
const [items, setItems] = React.useState(
{
product_id: 93,
quantity: 2
},
{
product_id: 22,
variation_id: 23,
quantity: 1
}
);
const { cart } = props;
useEffect(() => {
const products = Object.entries(cart).map(([key, { id, quantity }]) => ({
product_id: id,
quantity: quantity
}));
setItems(currentItems => ({ ...products, ...currentItems }));
}, [cart]);
您应该使用一个数组或一个 object 作为 state。您将两个单独的对象传递给 useState,用适当的键将它们包装在一个 object 中。 或使用数组。
it seems you have forgotten to add a wrap your initial object inside curly braces.
const [items, setItems] = useState([
{
product_id: 93,
quantity: 2,
},
{
product_id: 22,
variation_id: 23,
quantity: 1,
},
]);
然后
return [prod, ...currentItems];
作为建议:
最好制作新对象并将它们一次全部设置在 state 中。
const objectsToAdd = Object.values(cart).map(function (cartItem) {
return {
product_id: cartItem.id,
quantity: cartItem.quantity,
};
});
setItems((currentItems) => {
return [...objectsToAdd, ...currentItems];
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.