为了账号安全,请及时绑定邮箱和手机立即绑定

在循环中设置状态 React Native

在循环中设置状态 React Native

温温酱 2022-12-09 15:11:20
我有一些对象数组形式的道具,我用它们来更新我的“项目”状态。我能够遍历对象并构建包含“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。
查看完整描述

2 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

您不需要在循环中一次又一次地设置状态。相反,只是在数组上循环,获取项目并最终设置状态


   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]);


查看完整回答
反对 回复 2022-12-09
?
冉冉说

TA贡献1877条经验 获得超1个赞

您应该使用数组或对象作为状态。您将两个单独的对象传递给 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];

})


查看完整回答
反对 回复 2022-12-09
  • 2 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号