S
S
StepanSnigur2019-04-23 19:43:31
React
StepanSnigur, 2019-04-23 19:43:31

Is the code implemented correctly?

Hello. I just started learning Redux, created a store app. When you click on the "add to cart" button, the inCart checkbox of the product changes, and only then it is determined by this flag whether the product will be added to the cart or not. The question itself is: is the implementation correct? Or should it be done differently? Here is the cart code:

import React, { Component } from 'react';
import { connect } from "react-redux";

import Goods from './Goods';

class Magazine extends Component{

    goodsHandler = (items) => {
        let sum = 0;
        for (let item of items) {
            if (item.inCart) {
                sum += parseInt(item.price);
            }
        }
        return sum; //это сумма цен товаров в корзине, я отрисовываю именно ее
    }

    render() {
        return (
            <div>
                <h1>Total: <span>{this.goodsHandler(this.props.goods)}</span></h1>
                <Goods />
            </div>
        )
    }
}

let mapStateToProps = (state) => {
    return {
        goods: state
    }
}

export default connect(mapStateToProps)(Magazine);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-23
@StepanSnigur

Not right. In a good way, you should have a basket state with objects describing positions. At a minimum, this is the quantity and product id:

{
  product_id: "223af-b4535-54e21-31233-12a122-b453d",
  quantity: 2.
}

They are already in a cycle and display the positions of the basket, substituting the necessary goods.
Total will be more reliable to calculate in the reducer. The total value must be recalculated each time items are added/removed from the basket and their number changes. To do this, it will be convenient to add the price of the goods to the position object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question