使用react在Redux中修改数组

时间:2018-07-29 00:22:11

标签: javascript reactjs react-redux

无法从一系列购物车中删除商品。数组由组件组成,每个组件都有自己的删除按钮。当我按它时,我想从数组中删除该特定组件。有人可以帮忙吗?是的

case actionTypes.SHOP_DELETE_PRODUCT: {
        return {
            orders:[
            ...state.orders.slice(0, action.payload),
            ...state.orders.slice(action.payload + 1)
            ]
        };
    }
const deleteProduct = (index) => ({
type: actionTypes.SHOP_DELETE_PRODUCT,
payload: {
  index
}

});

deleteProductFunc(index){
  this.props.deleteProduct(index);

}

1 个答案:

答案 0 :(得分:1)

您正在使用的有效负载是具有索引属性的对象。您的减速器需要伸入有效载荷才能获得有效载荷的index属性:

case actionTypes.SHOP_DELETE_PRODUCT: {
  return {
     orders:[
       ...state.orders.slice(0, action.payload.index),
       ...state.orders.slice(action.payload.index + 1)
       ]
  };
}

另一种解决方案是仅使用索引作为有效载荷:

const deleteProduct = (index) => ({
    type: actionTypes.SHOP_DELETE_PRODUCT,
    payload: index
});