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

将对象转换为使用扩展运算符?

将对象转换为使用扩展运算符?

吃鸡游戏 2021-11-18 20:17:30
我在 redux 减速器中有一个案例,我使用 object.assign 来复制我的状态,我想将其转换为新的语法扩展运算符“...状态”,我该如何制作,不做突变!case INCREASE_QUANTITY: {      return Object.assign({}, state, {        cart: state.cart.map(item => {          if (item.product.id === action.productInfo.product.id) {            return Object.assign({}, item, {              quantity: action.quantity + 1,            });          }          return item;        }),      });    }
查看完整描述

2 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

Object.assign({}, item, { quantity: action.quantity + 1 });

变成

{ ...item, quantity: action.quantity + 1 }


case INCREASE_QUANTITY : {

    return {

        ...state,

        cart : state.cart.map(item => {

            if (item.product.id === action.productInfo.product.id) {

                return {

                    ...item,

                    quantity: action.quantity + 1

                }

            }

            return item;

        })

    };

}


查看完整回答
反对 回复 2021-11-18
?
动漫人物

TA贡献1815条经验 获得超10个赞

您打开一个对象字面量,首先...state将其展开到新对象中,然后使用cart属性(以及内部属性的相同概念):


case INCREASE_QUANTITY: {

  return {

    ...state,

    cart: state.cart.map(item => {

      if (item.product.id === action.productInfo.product.id) {

        return {

          ...item,

          quantity: action.quantity + 1,

        };

      }

      return item;

    }),

  };

}

通过按该顺序执行此操作,您可以确保cart(或quantity对于内部)覆盖点差中的属性。对象字面量中较晚的属性“胜过”较早的属性。


查看完整回答
反对 回复 2021-11-18
  • 2 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信