结账后反应本地redux清除购物车



用户成功签出后,我想清空购物车。目前,当用户结账并返回主屏幕时,商品仍在他们的购物车中。

Reducers文件:

let defaultState = {
// orders with cafeName as Key and list of items as a value
selectedItems: { items: [] },
};
let cartReducer = (state = defaultState, action) => {
switch (action.type) {
case "ADD_TO_CART": {
let newState = { ...state };
cafeName = action.payload.cafeName;
if (action.payload.checkboxValue) {
console.log("ADD TO CART");
newState.selectedItems = {
items: [...newState.selectedItems.items, action.payload],
};
} else {
console.log("REMOVE FROM CART");
newState.selectedItems = {
items: [
...newState.selectedItems.items.filter(
(item) => item.name !== action.payload.name
),
],
};
}
console.log(newState);
return newState;
}
default:
return state;
}
};
export default cartReducer;

我相信你可以通过制作新的动作类型来清除你的购物车,并将其添加到减速器中

CLEAR_CART

在减速器中,只返回默认状态,即空推车

...
case 'CLEAR_CART':
return defaultState
...

并通过在用户完成签出后发送它,将执行CLEAR_CART动作


尝试检查reduToolkithttps://redux-toolkit.js.org/tutorials/quick-start#create-a-redux-state切片,也用于redux-action和reducers 的更简单的编写

相关内容

  • 没有找到相关文章