Как исправить баг с отрицательной суммой товаров в корзине?

Числа в корзине становятся отрицательными:

5a36b67ceb4b4398328460.png

Items.jsx (родительский компонент)
import React, {Component} from 'react';

import Item from '../components/Item';
import Cart from '../components/Cart';

import '../css/shop.css';
import '../css/keyload.css';

class Items extends Component{
    constructor(props){
        super();
        this.state ={
            itemPrice: 0,
            price: 0,
            itemPrice: 0,
            title: []
        };
        this.handleCartPriceChange = this.handleCartPriceChange.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(id, price){
    // создадим новый массив, что бы не мутировать предыдущий, после чего методом splice удалим элемент и запишем в state
    const newTitles = [...this.state.title];
    newTitles.splice(id, 1);
    const itemPrice = this.state.itemPrice;
    this.setState({title: newTitles, price : this.state.price - price})
}
handleCartPriceChange(price, title, itemPrice){
    this.setState({ itemPrice: itemPrice, price: this.state.price + price, title: [...this.state.title, title]});
    console.log(this.state.itemPrice);
}
    render(){
    return(
        <div className="wrap">
            <Cart onDelete={this.handleDelete} itemPrice={this.state.itemPrice} title={this.state.title} price={this.state.price} />
            <section className="shop">
                <div className="wrap_container">
                {this.props.items.map(item =>
                     <Item itemPrice={item.price} onCartItemDelete={this.handleDelete} title={item.title} price={item.price} onCartPriceChange={this.handleCartPriceChange} key={item.id} shirt ={item.img}/>
                )
                }
                </div>
            </section>
        </div>
    );
}
}
export default Items;

Cart.jsx (корзина)
import React, {Component} from 'react';

import Button from './Button';

import cart from './img/cart.svg';
export default class Cart extends Component{
    constructor(props){
        super();
    }
    render(){
        var price = this.props.price;
        var title = this.props.title;
        return(
            <aside className="cart">
            <div className="wrapper">
                    <img src={cart} alt=""/>
                    <div className="priceOutput">
                        <span className={price<2000? 'price' : 'price_red'}>{`${price ? price +'$' : 'Add item to cart' }` }</span>
                        <hr/>
                        <div className="cart_history">
                            <ul>{title.map((n, i) =>
                                <li key={i} className="item">{n}<i onClick={()=>this.props.onDelete(i, this.props.itemPrice)} className="material-icons">delete</i></li> 
                            )}</ul>
                        </div>
                        <Button className="btn_submit">Submit</Button>
                    </div>
            </div>
            </aside>            
        );
    }
}

Item.jsx
import React, {Component} from 'react';

import Button from './Button';

class Item extends Component{
    constructor(props){
        super(props);
        this.state={
            btn_children: 'ADD'
        };
        this.onCartPriceChange = this.onCartPriceChange.bind(this);
        this.onCartPriceOver = this.onCartPriceOver.bind(this);
    }
    onCartPriceChange(){
        this.setState({ btn_children: this.props.price + '$',
    })
    }
    onCartPriceOver(){
        this.setState({btn_children: 'ADD'})
    }
    render(){
    return(
        <div className="shop__item">
            <img className="item" src={this.props.shirt} alt=""/>
            <div className="title">
                <a href="#" className="descr">подробнее</a>
                <Button onMouseOver={this.onCartPriceChange} onMouseOut={this.onCartPriceOver} onClick={()=> this.props.onCartPriceChange(this.props.price, this.props.title, this.props.itemPrice)} className="btn_buy">{this.state.btn_children}</Button>
            </div>
        </div>        
    );
}
}
export default Item;
  • Вопрос задан
  • 244 просмотра
Решения вопроса 1
0xD34F
@0xD34F Куратор тега React
Нехорошее решение - хранить в корзине сумму. Из-за этого вы при удалении элемента не можете правильно определить, сколько надо вычесть. Лучше так - хранить не сумму, а сами элементы. Когда сумма понадобится - посчитать её. Например.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы