[英]Remove Item Without Mutating State in Redux
我尝试的第一件事是:
const initialState = {
items: {},
showCart: false,
showCheckout: false,
userID: null
};
export default function reducer(state=Immutable.fromJS(initialState), action) {
case 'REMOVE_FROM_CART':
return state.deleteIn(['items', String(action.id)]);
}
当控制台记录上面的deleteIn时,它实际上确实正确地从Map中删除了该项目。 但是,该应用程序不会再次重新渲染,因为我认为我正在改变state(?)。 (mapStateToProps被调用,但没有新状态)。
所以接下来我尝试了这个:
case 'REMOVE_FROM_CART':
const removed = state.deleteIn(['items', String(action.id)]);
const removeItemState = {
...state,
items: { removed }
}
return state.mergeDeep(removeItemState);
但是我只是将删除的项目再次添加到项目中,从而创建了重复项。
我该如何处理?
深入克隆状态后,您是否尝试过删除项目?
case 'REMOVE_FROM_CART':
const removeItemState = {
...state
items: {
...state.items
}
};
delete removeItemState.items[String(action.id)];
return removeItemState;
如何减少?
case 'REMOVE_FROM_CART':
return {
...state,
items: Object.keys(state.items).reduce((acc, curr) => {
if (curr !== action.id) acc[curr] = state.items[curr];
return acc;
}, {})
};
发布更多代码(例如我的reducers设置) 可能会有所帮助,但这是怎么回事:
首先,此代码是从状态中删除项目的正确方法。
return state.deleteIn(['items', String(action.id)]);
但是,由于我使用的是immutable
库,而不是我的CombineReducers使用redux-immutable
,因此无法正确处理我的状态。 这使我可以做state.cart.items
类的state.cart.items
(在mapStateToProps中),在这里我本应该使用state.getIn(['cart', 'items'])
。
神奇地改变它使删除工作。
感谢Reactiflux不可变Slack频道中的@jslatts来帮助您解决这个问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.