我在redux reducers中有一个案例,我使用了object.assign来获取我的状态的副本,并且我想将其转换为新的语法散布运算符“ ... state”,我该如何做,< / p>
不做突变!
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;
}),
});
}
答案 0 :(得分:3)
您打开一个对象文字,以...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
)会覆盖价差中的属性。对象文字中的较新属性“胜过”较早的属性。
答案 1 :(得分:1)
events.js:174 Uncaught TypeError: t.addEventListener is not a function
at v (events.js:174)
at e.handleGeometryChanged_ (Feature.js:210)
at e (events.js:41)
at e.dispatchEvent (Target.js:101)
at e.notify (Object.js:151)
at e.set (Object.js:170)
at e.setProperties (Object.js:186)
at new e (Feature.js:108)
at getPolygon (maskedPolygon.js:319) <-- this is the second line in my code sample above
at <anonymous>:1:1
成为
Object.assign({}, item, { quantity: action.quantity + 1 });
{ ...item, quantity: action.quantity + 1 }