React js与redux购物车

soat7uwm  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(149)

为什么当我点击“添加到购物车”时,即使我点击了很多次,我也只得到一次更改,而且 cout 没有进入购物车,我该如何解决这个问题?我希望如果点击了按钮,那么“购物车”数组将保存该值,有一次更改,但只有一次更改,并且许多项目没有加起来

应用程序.js.

<> 

<div className="button-cart">
                    <div className="btn">
                      <img src={minus} onClick={this.props.handleMinus} />
                      <h1>{this.props.cout}</h1>
                      <img src={plus} onClick={this.props.handlePlus} />
                    </div>
                    <div className="button">
                      <button onClick={this.props.handleAdd}>
                        Add to cart
                      </button>
                    </div>
                  </div>
                  {this.props.cart.map((item, index) => (
                    <div key={index}>
                      <p>{item.title}</p>
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        </div>
      </>
    );
  }
}
const mapToProps = (state) => {
  return {
    Product: state.Product,
    cart: state.cart,
    cout: state.cout,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    handleMinus: () => dispatch({ type: "minus_button" }),
    handlePlus: () => dispatch({ type: "plus_btn" }),
    handleAdd: () => dispatch({ type: "ADD_TO_CART" }),
  };
};

export default connect(mapToProps, mapDispatchToProps)(App);

存储.js

import { createStore} from 'redux';
const initialState = {  // store
         Product: [
      {
          id:1,
        title: "SNEAKER COMPANY",
        brand: "Fall Limited Edition Sneakers",
        desc: "These low-profile sneakers are your perfect casual wear companion. Featuring a durable rubber outer sole, they’ll withstand everything the weather can offer.",
        price: 125.0,
        images: imgT1,
      }
    ],
    cout:1,
    total:0,
    cart:[]
}

const rootReducer = (state= initialState,action) =>{

    if(action.type === 'plus_btn' ){
        return {...state, cout: state.cout + 1}
    }else if(action.type === 'minus_button' && state.cout > 1){
        return {...state, cout: state.cout - 1}
    }
//I want if the button is clicked then the 'cart' array will hold the value,

    if(action.type === 'ADD_TO_CART'){
        return {...state, cart: state.Product}
    }

      return state
  }

const store = createStore(rootReducer)
export default store;
wmomyfyw

wmomyfyw1#

您的connect()HOC应该有2个参数connect()(Map到属性的状态,Map到属性的调度)

相关问题