Что вам нужно сделать, так это, когда вы получите товары из своей корзины, просмотреть каждый товар и добавить количество для каждого из них.И добавьте итоговое значение в состоянии для общей суммы всех продуктов.
constructor(props) {
super(props);
this.state = {
data:[],
customer: '',
redirectToReferrer: false,
cart: [],
cartItems: [],
totalPrice: 0
clicked: '' };
this.onChangeQty = this.onChangeQty.bind(this);
}
componentDidMount() {
const retrieved = localStorage.getItem("cartItem");
const arr = JSON.parse(retrieved);
axios.post('http://localhost/Auth/api/customers/show_cart.php', arr,
{
headers: {'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'}
} )
.then(response => {
let myItems = [];
response.forEach(item => {
myItems.push({id: item.id, name: item.name, qty: 1, price: item.price, total: item.price});
})
this.setState({
cartItems :myItems
});
})
.catch(error => {
if (error) {
console.log("Error"); }
});
}
Метод OnChange должен найти выбранный продукт и обновить его количество, а totalPrice:
onChangeQty(sid,e)
{
const items = this.state.cartItems;
const item = items.find(item => item.id === sid);
const index = items.indexOf(item);
item.qty = e.target.value;
item.total = item.qty * item.price;
items[index] = index;
let totalPrice = 0;
items.forEach(item => {
totalPrice += item.qty * item.price;
});
this.setState({
cartItems: items,
totalPrice
});
}
и в формате html.Вы можете показать общую цену как
{this.state.totalPrice}
, и если вы хотите получить сумму по каждому предмету, вы можете просто проверить ее по
this.state.cartItems.forEach(item => {
console.log(item.total);
})