在循环中设置状态 React Native

我有一些对象数组形式的道具,我用它们来更新我的“项目”状态。我能够遍历对象并构建包含“product_id”和“数量”的对象。当我只是 console.log 时,我可以看到正确的数据,但是当我尝试更新状态时,我得到了错误"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。


温温酱
浏览 88回答 2
2回答

跃然一笑

您不需要在循环中一次又一次地设置状态。相反,只是在数组上循环,获取项目并最终设置状态   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]);

冉冉说

您应该使用数组或对象作为状态。您将两个单独的对象传递给 useState,用适当的键将它们包装在一个对象中。或使用数组。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];  作为一个建议:最好制作新对象并将它们一次全部设置在状态中。const objectsToAdd = Object.values(cart).map(function (cartItem) {  return {    product_id: cartItem.id,    quantity: cartItem.quantity,  };});setItems((currentItems) => {  return [...objectsToAdd, ...currentItems];})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript