I am trying to remove an item, I send the item information but when I receive it in the reducer I do not know how to do it so that I delete it from the array. Try indexOf but I do not know how to return it.
I'm learning React and Redux, sorry for the inconvenience.
I can not think of how I can proceed.
shopActions.js
import actionTypes from '../constants/actionTypes';
const addProduct = (name, description, price) => ({
type: actionTypes.SHOP_ADD_PRODUCT,
payload: {
name,
description,
price
}
});
const removeProduct = (item) => ({
type: actionTypes.SHOP_REMOVE_PRODUCT,
payload: item
});
export default { addProduct, removeProduct };
Shop.js
import actionTypes from '../constants/actionTypes';
const initialState = {
orders: []
};
const shopReducer = (state = initialState, action) => {
switch(action.type) {
case actionTypes.SHOP_ADD_PRODUCT: {
return Object.assign({}, state, {
orders: [...state.orders, action.payload]
});
}
case actionTypes.SHOP_REMOVE_PRODUCT: {
console.log(action.payload)
return ;
}
default:
return state;
}
};
export default shopReducer;
Products.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ProductItem from '../../components/ProductItem';
import CartItem from '../../components/CartItem';
import './Products.css';
// @Actions
import productsActions from '../../actions/productsActions';
import shopActions from '../../actions/shopActions';
class Products extends Component {
componentDidMount() {
// Este getProducts debería conectarse a un servicio y traer de ahi los productos
// Para nuestro jemeplo, los productos están hardcodeados (puestos a mano) en el reducer
// Si quieren agregar o modificar productos, lo hacen directamente desde el reducer
this.props.getProducts();
// Dejo este getProducts aquí como ejemplo de donde debería llamarse para traer la información desde un servicio
}
addProduct(name, description, price) {
this.props.addProduct(name, description, price);
}
removeProduct(item){
this.props.removeProduct(item);
}
render() {
const { products, shop } = this.props;
const renderProducts = products.list ? products.list.map((products, index) => {
return (
<ProductItem
index={index}
product={products}
button={<button className='btn btn-primary' onClick={() => {this.addProduct(products.name, products.description, products.price);}}>
Agregar al carrito</button>}/>
);
}) : null;
// Lo siguiente son los productos agregados al carrito. Lo mismo que el caso anterior,
// Mover todo a componentes, identificar y crearlos
// Por ejemplo un componente llamado <Orders> que reciba por props los productos
// Podrían crear una acción para quitar el producto del carrito
const orders = shop.orders.length ? shop.orders.map((products, index) => {
return (
<CartItem product={products} button={<button className='btn btn-danger' onClick={() => {this.removeProduct(products);}}>
BORRAR</button>} />
);
}) : <p>No hay productos en el carrito</p>;
return (
<div>
<h1>Productos</h1>
<div className='groupOfCards'>
{renderProducts}
</div>
<h1>Carrito</h1>
<table class="table productTable">
<thead class="thead-dark">
<tr>
<th scope="col">Item</th>
<th scope="col">Cantidad</th>
<th scope="col">Precio</th>
<th scope="col">Borrar</th>
</tr>
</thead>
<tbody>
{orders}
</tbody>
</table>
</div>
);
}
}
/*
connect conecta la aplicación al store. Permite agregar datos y funciones a
las props.
*/
export default connect(
state => {
return {
products: state.productsReducer, // Saco los productos del reducer
shop: state.shopReducer
}
},{
addProduct: shopActions.addProduct,
removeProduct: shopActions.removeProduct, // Uso una acción para agregar al carrito
getProducts: productsActions.getProducts
}
)(Products);
答案 0 :(得分:0)
Ok, if you want to render the UI when you add or remove any element in your card the adding and deletion of an item should happen in an immutable way, I can see for adding you are using Object.assign which is fine in the same way when removing you need to use the es6 filter on the existing array and set the state.
答案 1 :(得分:0)
Assuming item.name
is a unique identifier(which it shouldn't be. you must use a
save a unique id with it too) you can filter out the product from array and return it like
case actionTypes.SHOP_REMOVE_PRODUCT: {
const newOrders = state.orders.filter((item) => item.name !== action.payload.name);
return {...state, orders: newOrders }
}
答案 2 :(得分:0)
Assume there is some unique key id
exists in the product records.
case actionTypes.SHOP_REMOVE_PRODUCT: {
let filteredOrder = state.orders.filter((product)=>product.id!=action.payload.id);
//filteredOrder will hold record not having action.payload
return
Object.assign({}, state, {
orders: [...filteredOrder]
})
}
答案 3 :(得分:0)
就像使用Object.assign将商品添加到购物车中一样,要从购物车中删除商品,请先使用看起来合适的任何数组方法(例如拼接,过滤器)从orders数组中删除商品,然后使用Object.assign更改状态对象中的顺序。
case actionTypes.SHOP_REMOVE_PRODUCT: {
let orders = state.orders.filter((item) => item !== action.payload);
return Object.assign({}, state, {
orders: orders
});
}