【问题标题】:how to remove an item from cart in react native using redux如何使用redux从购物车中删除商品
【发布时间】:2021-07-15 15:55:04
【问题描述】:

当我从购物车中移除商品时,我遇到了挑战,购物车并未从购物车中移除商品,而是添加了空白商品

这是购物车屏幕

ScrollView>
       {this.props.cartItems.map((item, index) => {
          return (
            <Menu key={index} style={{ padding: 0.5 }}>
              <MenuImage source={item.image}/>
                <MenuInfor>
                  <Text dark bold>{item.name}</Text>
                  <Text dark small>{item.info}</Text>
                  <Text dark bold>${item.price}</Text>
                </MenuInfor>
              <TouchableOpacity
                onPress={() => this.props.removeItem(item.id)}            
                style={{alignItems: 'flex-end', justifyContent: 'flex-end', alignSelf: 'flex-end'}}
              >
                <AntDesign name="minuscircleo" size={30} color="#000" />
              </TouchableOpacity>
            </Menu>
                )
            })}
      </ScrollView>

以下是我的action.js文件

 const addToCart = (id, count) => (
  {
    type: 'ADD_TO_CART',
    payload:{
      id,
      count,
    }

  }
);

// removeFromCart
const removeFromCart = (id) => (
  {
    type: 'REMOVE_FROM_CART',
    id,
    count,
  }
);

以下是我的 reducer.js 文件

const cartItems = (state = [], action) => {
    switch (action.type) {
        case 'ADD_TO_CART':{
            return [...state, action.payload ]            
          }
        case 'REMOVE_FROM_CART':    
             
        return [...state, state.filter(cartItem => cartItem.id !== action.payload.id)]
        
        case 'CLEAR_CART':
        return {
        ...state,
        cartItems: ['']
        }
      }
    return state
}
export default cartItems

【问题讨论】:

  • 能分享一下reducer的初始状态吗?
  • 我相信你在reducer 'REMOVE_FROM_CART' 部分的return 语句有些不正确。我不确定如何准确解决您的问题,但您的其他返回语句正在返回对象,而您的删除购物车返回一个数组。你可以试试这样的:return { ...state, cartItems: state.cartItems.filter(....)};

标签: react-native redux react-redux


【解决方案1】:

查看您提供的代码....我认为这是您代码中唯一的错误。

case 'REMOVE_FROM_CART':   
   return {
        ...state,
        cartItems: state.cartItems.filter((cartItem) => cartItem.id != 
        action.payload.id)
      };

【讨论】:

  • 我已经应用了那个代码,但是它说 undefined 不是一个对象(评估 ''state.cartitems.filter) 这个代码在我点击购物车中的删除项目按钮后出现
  • 能否分享一下你的reducer初始状态。我假设您的状态中有一个 cartItems 数组....如果您的状态是您正在更新的数组,那么 state.cartItems.filter 应该替换为 state.filter
猜你喜欢
  • 2015-07-05
  • 2022-08-23
  • 1970-01-01
  • 2018-10-19
  • 2013-10-17
  • 2021-07-26
  • 1970-01-01
  • 2018-07-22
相关资源
最近更新 更多