如何在注销时删除购物车项目

How to remove cart items on signing out

我正在从 localStorage 中删除 cartItems,但购物车仍然显示所选商品。

注销的 Redux 操作。

export const signout = () => (dispatch) => {
      localStorage.removeItem('userInfo'); 
      localStorage.removeItem('cartItems');
      localStorage.removeItem('shippingAddress');  
      dispatch({type: USER_SIGNOUT})
}

正在购物车屏幕上获取购物车项目。

const cart = useSelector(state=> state.cart);
const {cartItems} = cart;

登录reducer

export const userSigninReducer = (state={},action) => {
    switch(action.type){
        case USER_SIGNIN_REQUEST:
            return {loading:true};
        case USER_SIGNIN_SUCCESS:
            return {loading: false,userInfo: action.payload};
        case USER_SIGNIN_FAIL:
            return {loading: false,error: action.payload};
        case USER_SIGNOUT:
            return {};
            default:
            return state;
    }
}

看这条线

const cart = useSelector(state=> state.cart);

我怀疑您有一个 cart reducer,并且您正在从该减速器获取数据并将其显示在 UI 中。

注销时,您要确保清除本地存储并清除用户详细信息。

dispatch({type: USER_SIGNOUT})

解决方案:您还需要dispatch对购物车减速器再执行一项操作,以便再次重置购物车详细信息。

添加更多操作dispatch({type: "CART_RESET"});以便您可以重置购物车减速器,

export const signout = () => (dispatch) => {
      localStorage.removeItem('userInfo'); 
      localStorage.removeItem('cartItems');
      localStorage.removeItem('shippingAddress');  
      dispatch({type: USER_SIGNOUT});
      // as you are removing stuffs from localStorage
      // you also need to reset the data from reducer
      dispatch({type: "CART_RESET"});
}

所以你的 cart reducer handler 应该看起来像这样

case "CART_RESET": return { ...state, cartItems: [] }

这将确保您在退出时重置购物车, 在重置或卸载时,如果需要,也可以按照相同的做法重置其他减速器数据。