【问题标题】:Incorrect Item is being removed from React Native Redux正在从 React Native Redux 中删除不正确的项目
【发布时间】:2021-09-28 06:19:02
【问题描述】:

我在 react native 应用程序中有以下用于购物车的 redux-reducer。问题是,当我尝试删除购物车的第一项时,只有列表中的最后一项被删除。如何解决此错误?

购物车操作:

export const removeFromCart = (payload) => {
  return {
    type: REMOVE_TO_CART,
    payload,
  }
}

const cartItems = (state = [], action) => {
  switch (action.type) {
    case ADD_TO_CART:
      //destructure the payload (which is the item) and take id
      const {_id} = action.payload;
      //check if there are duplicates
      const dupe = state.find(obj => obj._id === _id);
      //if duplicates, return state, else return state with the new payload
      return dupe ? state : [...state, action.payload];
    case REMOVE_TO_CART:
      return state.filter(cartItem => cartItem !== action.payload);
    case CLEAR_TO_CART:
      //return empty state which clears cart
      return (state = []);
  }
  //return the state
  return state;
};

购物车组件代码:

<IconButton
  icon="delete"
  color={"red"}
  size={25}
  onPress={() => {
  toggleModal();
  props.removeFromCart(item);
  Toast.show({
       type: "info",
       position: "top",
       text2: `${item.name.substring(0, 15)}... has been removed from cart!`,
       topOffset: 60,
    }}/>

//loop through the states from the redux store to convert into props so they can be used in this screen
const mapStateToProps = state => {
  const {cartItems} = state; //state coming from store
  return {
    cartItems: cartItems,
  };
};

//for grabbing actions from cartActions and adding and removing products
const mapDispatchToProps = dispatch => {
  return {
    clearCart: () => dispatch(actions.clearCart()),
    removeFromCart: item => dispatch(actions.removeFromCart(item)), //deleting a single item
  };
};

【问题讨论】:

    标签: react-native redux react-redux e-commerce cart


    【解决方案1】:

    你能改吗

    return state.filter(cartItem => cartItem !== action.payload);
    

    到:

    return […state.filter(cartItem => cartItem.id !== action.payload.id)];
    

    【讨论】:

    • 相同的结果。只是删除购物车中的最后一项,而不是我想要删除的东西。它与实际购物车本身的代码有关吗?我已经更新了帖子。
    • 您能确认过滤器返回的项目数正确吗?
    • 是的。例如,如果我在购物车中有 3 件商品并删除了一件商品,则会退回 2 件商品。但是,它始终是列表中的最后一项,总是被删除。
    • 虽然这不一定能解决问题,但它仍然是从状态中删除对象的更好方法。我将错误的项目传递给 redux,所以它不能正常工作。谢谢,传奇!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2016-04-07
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多